How do I save my print statement in a list? Python [closed]

最后都变了- 提交于 2019-12-20 07:55:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!