zak*_*191 0 python merge file-io list
我有两个列表已经按需要排序,我需要将它们放入一个文件中,如下例所示:
list1 = [a, b, c, d, e]
list2 = [1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)
输出文件应如下所示:
a1
b2
c3
d4
e5
Run Code Online (Sandbox Code Playgroud)
我是相当新的python,所以我真的不知道怎么做文件写.我读取使用with open(file, 'w') as f:是一种更好/更简单的方式来启动写入块,但我不确定如何合并列表并打印它们.我可以将它们合并到第三个列表中并将其打印到文件中,print>>f, item但我想看看是否有更简单的方法.
谢谢!
延迟编辑:查看我的列表,它们的长度不一样,但所有数据都需要打印.因此,如果list2转到7那么输出将需要是:
a1
b2
c3
d4
e5
6
7
Run Code Online (Sandbox Code Playgroud)
反之亦然,其中list1可能比list2长.
使用zip()函数组合(即压缩)两个列表.例如,
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = [1, 2, 3, 4, 5]
zip(list1, list2)
Run Code Online (Sandbox Code Playgroud)
得到:
[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]
Run Code Online (Sandbox Code Playgroud)
然后,您可以格式化输出以满足您的需要.
for i,j in zip(list1, list2):
print '%s%d' %(i,j)
Run Code Online (Sandbox Code Playgroud)
收益:
a1
b2
c3
d4
e5
Run Code Online (Sandbox Code Playgroud)
更新:
如果您的列表长度不等,则使用 itertools.izip_longest()的方法可能对您有用:
import itertools
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = [1, 2, 3]
for i,j in itertools.izip_longest(list1, list2):
if i: sys.stdout.write('%s' %i)
if j: sys.stdout.write('%d' %j)
sys.stdout.write('\n')
Run Code Online (Sandbox Code Playgroud)
得到:
a1
b2
c3
d
e
Run Code Online (Sandbox Code Playgroud)
请注意,如果您使用的是Python 3,则可以使用该print()功能.我在write()这里使用以避免项目之间的额外空白.
| 归档时间: |
|
| 查看次数: |
777 次 |
| 最近记录: |