连接列表以在for循环中列出

时间:2014-08-06 20:42:07

标签: python list for-loop python-3.x concatenation

瞄准它将多个列表连接到for循环中的一个列表。目前,输出打印的是地图对象,而不是合并在一个列表中的所有内容。

目录

enter image description here

每个样本文件的内容

aa - http://cc
bb - http://bb
cc - http://aa
aa - aa - http://cc
bb - bb - http://bb
cc - cc - http://aa
aa - aa - aa - http://cc
bb - bb - bb - http://bb
cc - cc - cc - http://aa

代码

import os

cwd = os.getcwd()

for fn in os.listdir(cwd):
    with open(fn, "r+") as f, open(cwd + "\\all.txt", "r+") as f2:
        lines = f.readlines()

        my_list = [fn + " - " + x for x in lines]

        concatenated_list = map(" ".join, zip(my_list))
        print(concatenated_list)

结果

电流

C:\case.py
<map object at 0x0000000002CB7BE0>
<map object at 0x0000000002CB7B00>
<map object at 0x0000000002CB79E8>
<map object at 0x0000000002CB7E10>
<map object at 0x0000000002CB7A90>
<map object at 0x0000000002CB78D0>

预期

C:\Users\r\Desktop\test>C:\Users\r\Desktop\case.py
[]
['sample.txt - aa - http://cc\n', 'sample.txt - bb - http://bb\n', 'sample.txt -
 cc - http://aa\n', 'sample.txt - aa - aa - http://cc\n', 'sample.txt - bb - bb
- http://bb\n', 'sample.txt - cc - cc - http://aa\n', 'sample.txt - aa - aa - aa
 - http://cc\n', 'sample.txt - bb - bb - bb - http://bb\n', 'sample.txt - cc - c
c - cc - http://aa\n','sample2.txt - aa - http://cc\n', 'sample2.txt - bb - http://bb\n', 'sample2.tx
t - cc - http://aa\n', 'sample2.txt - aa - aa - http://cc\n', 'sample2.txt - bb
- bb - http://bb\n', 'sample2.txt - cc - cc - http://aa\n', 'sample2.txt - aa -
aa - aa - http://cc\n', 'sample2.txt - bb - bb - bb - http://bb\n', 'sample2.txt
 - cc - cc - cc - http://aa\n'...

3 个答案:

答案 0 :(得分:2)

在Python 3.x中,map()返回迭代器,而不是列表。试试这个:

concatenated_list = []
# Then in your for loop...
  concatenated_list += [" ".join(x) for x in zip(my_list)]

+=将所有列表连接在一起。

也不要重载list关键字。您不想覆盖内置函数的名称。如果您在Padraic的答案中使用了该方法,那么它将会失败,因为Python认为您正在尝试将list作为函数调用,而不是内置list()函数。

答案 1 :(得分:1)

使用list(concatenated_list) mapzippython3中的迭代器,也不要使用列表作为变量名称,它会隐藏内置list

           my_list =  [fn + " - " + x for x in lines]
           concatenated_list = map(" ".join, [x for x in zip(my_list)])
           print (list(concatenated_list))

答案 2 :(得分:-1)

concatenated_list = list(map(“”。join,zip(my_list))) 我同意Padraic,将列表放在地图前面