问题
How do I save my print statement in a list?
for i in range(len(values)):
for j in range(len(values)):
print (values[0]+values[i])+values[j]
回答1:
Don't use print if you wanted to add values to a list. Just add them to a list directly:
result = []
for i in range(len(values)):
for j in range(len(values)):
result.append(values[0] + values[i] + values[j])
You can loop over values
directly here:
result = []
for i in values:
for j in values:
result.append(values[0] + i + j)
which can be combined into a list comprehension:
result = [values[0] + i + j for i in values for j in values]
回答2:
You can use a variable to store the result,
result = []
for i in range(len(values)):
for j in range(len(values)):
res = (values[0]+values[i])+values[j]
print res
result.append(res)
or do the following to slightly optimize code above:
result = []
for i in range(len(values)):
for j in range(len(values)):
result.append((values[0]+values[i])+values[j])
print result[-1]
Better still, you can use a list comprehension to simplify this and create the end result
:
result = [values[0] + i + j for i in values for j in values]
You can of course then print these later using a simple
for res in result:
print res
回答3:
You could use a list comprehension:
results = [values[0] + val_i + val_j for val_i in values for val_j in values]
来源:https://stackoverflow.com/questions/27970483/how-do-i-save-my-print-statement-in-a-list-python