Python:将元素添加到列表时出现问题
将函数打印的结果添加到列表中时遇到了一个小问题。情况就是这样。该函数打印一些结果这样Python:将元素添加到列表时出现问题
result1
result2
result3
如何将它们添加到列表中,看到他们像mylist=['result1', 'result2', 'result3']
?因为,在我的情况,我有一个工作循环,它计算使用由我编写的功能每一种情况下(并打印像上面的结果),但使用附加功能,它打印是这样的:
['result1'], ['result1', 'result2'], ['result1', 'result2', 'result3'].
中当然,使用最后的结果,['result1', 'result2', 'result3']
,对我来说应该是完美的,但是我得到了像上面这样的三个列表。我只做最后一个清单,那个有三个结果的清单?
好吧,我要把一些代码放在这里,以便更具体。我有一个很大的字符串(我不会在这里写它,因为并不重要)。我的功能是从该字符串拆分一些特定的网址。该功能是这样的:
def fileref(string, file):
start=string.find(file) + 28
end=string.find('</ref', start)
file=string[start:end]
return file
我有这个名单与使用功能参数:
files55_2=['f55_1.jpg', 'f55_2.jpg', 'f55_3.txt', 'f55_4.mp4']
然后,一个循环我这样做:
for i in files55_2:
print fileref(string, i)
它打印我这些网址:
https://myapi.net/file1
https://myapi.net/file2
https://myapi.net/file3
https://myapi.net/file4
现在我需要一个解决方案,具有所有这些元素,像这样的列表:
mylist=['https://myapi.net/file1', 'https://myapi.net/file2', 'https://myapi.net/file3', 'https://myapi.net/file4']
我希望我现在更具体。无论如何感谢您的答案!
将函数追加到列表中,然后在函数外部打印,可能会更好。
>>> def append():
... l = []
... for i in range(3):
... l.append(str(i))
... return l
...
>>> l = append()
>>> l
['0', '1', '2']
或者,如果你已经在运行函数之前有名单,你会不会需要归还。
>>> def append(l):
... for i in range(3):
... l.append(str(i))
...
>>> l = []
>>> append(l)
>>> l
['0', '1', '2']
谢谢你,你的解决方案似乎是我想要的。 – 2012-03-02 17:00:19
另请参阅我的更新回答 – BioGeek 2012-03-02 17:16:17
@BioGeek:我在发布问题之前尝试了这一点,它向我展示了列表的相同增量。 – 2012-03-02 17:40:39
在你的功能,你正在逐步建立您的清单,每一步之后打印出清单,这样的事情:
l = []
for i in range(1,4):
l.append("result {0}".format(i))
print l
输出:
['result 1']
['result 1', 'result 2']
['result 1', 'result 2', 'result 3']
你想要做的是打印在完成创建之后将其列出,例如:
l = []
for i in range(1,4):
l.append("result {0}".format(i))
print l
输出:
['result 1', 'result 2', 'result 3']
编辑:在所提供的代码,更改这些行:
for i in files55_2:
print fileref(string, i)
到:
mylist = []
for i in files55_2:
mylist.append(fileref(string, i))
print mylist
'map(“result {}”。format,range(1,4))'should too too ... – Gandaro 2012-03-02 13:22:20
在for循环中,您可以使用 “其他” 接近,这之后执行循环已完成:
for ...
...
else
//here you can add your results to list after loop has finished
你能举一个你正在使用的功能的例子吗?此外,它可能有助于在此添加一些空白;)编辑 - 某人已经在 – 2012-03-02 13:14:24
中输入空格请显示您的代码! – 2012-03-02 13:14:51
您是否在循环打印获得打印的增量列表让您感觉有三个列表?或者,你实际上得到三个List对象?代码请。 – Nishant 2012-03-02 13:16:15