2012-07-10 72 views
0

我已排序他們怎麼需要是兩個列表,我需要他們投入到一個文件中,這樣的例子:打印兩個預排序列表到一個輸出文件中的巨蟒

list1 = [a, b, c, d, e] 
list2 = [1, 2, 3, 4, 5] 

輸出文件應看起來像:

a1 
b2 
c3 
d4 
e5 

即時通訊相當新的python,所以即時通訊不是真的都知道如何做文件編寫。我使用with open(file, 'w') as f:讀取是一種更好/更簡單的方式來啓動寫入塊,但我不確定如何合併列表並將它們打印出來。我可以將它們合併到第三個列表中,然後使用print>>f, item將該列表打印到文件中,但我想知道是否有更簡單的方法。

謝謝!延遲編輯:查看我的列表,他們不會總是相同的長度,但所有數據需要打印不管。所以,如果列表2跑到7,然後再輸出將需要:

a1 
b2 
c3 
d4 
e5 
6 
7 

或反之亦然,其中list1的可能較長列表2。

回答

6

使用zip()函數來合併(即壓縮)你的兩個列表。例如,

list1 = ['a', 'b', 'c', 'd', 'e'] 
list2 = [1, 2, 3, 4, 5] 

zip(list1, list2) 

給出:

[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] 

然後你可以格式化輸出,以滿足您的需求。

for i,j in zip(list1, list2): 
    print '%s%d' %(i,j) 

產生:

a1 
b2 
c3 
d4 
e5 

更新

如果你的列表是不等長,這種方法使用 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') 

得到:

a1 
b2 
c3 
d 
e 

請注意,如果您使用的是Python 3,則可以使用print()函數。我在這裏使用write()以避免項目之間出現多餘的空白。

+0

真棒,這似乎是工作。我將'%d%d'改爲'%s%s',因爲在我的程序中它的技術字符串(抱歉,從未指定)。有沒有辦法修改這個,以便如果一個列表更長,那麼另一個它仍然會打印出所有的值(即使它們沒有匹配)? – zakparks31191 2012-07-10 17:30:52

+0

hm我假設這個鏈接中的'map'語句會在for循環之前出現? – zakparks31191 2012-07-10 17:36:05

+0

嗯這個工程,但給一些堅果看輸出。它是正確的,但每行都在括號內,每個項目都有單引號。這是使用itertools的「特性」,還是我可以修改這些東西? – zakparks31191 2012-07-10 17:46:24

2

應該使用zip功能:

此函數返回的元組,其中,第i個元組包含來自每個參數序列或iterables的第i個元素的列表。

for a, b in zip(lis1, list2): 
write(a, b) 
0

一個內膽:

print "\n".join(("%s%s" % t for t in zip(list1, list2))) 
+0

'print「\ n」 .join((「%s%s」%t爲zip(list1,list2)))''更短:) – 2012-07-10 17:46:36

+0

@MariaZverina哈哈不錯,自從我pythoned之後已經有一段時間了。忘了你不需要明確元組擴展 – 2012-07-11 01:39:27

1
>>> list1 = ['a', 'b', 'c', 'd', 'e'] 
>>> list2 = [1, 2, 3, 4, 5] 
>>> map(lambda x:x[0]+str(x[1]),zip(list1,list2)) 
['a1', 'b2', 'c3', 'd4', 'e5'] 

沒有zip()

>>> map(lambda x,y:x+str(y), list1,list2) 
['a1', 'b2', 'c3', 'd4', 'e5'] 

編輯:If the list2 is list2 = [1, 2, 3, 4, 5,6,7]然後用izip_longest

>>> from itertools import zip_longest 
>>> [y[0]+str(y[1]) if y[0]!=None else y[1] for y in izip_longest(list1,list2,fillvalue=None)] 
['a1', 'b2', 'c3', 'd4', 'e5', 6, 7] 
+2

+1這是更漂亮的方式,但對於新手來說是不可理解的 – 2012-07-10 17:33:45

0

Simples ......愛你的Python :)

>>> from itertools import * 
>>> L1 = list("abcde") 
>>> L2 = range(1,8) 
>>> [(x if x != None else '') + str(y) for (x,y) in izip_longest(L1,L2)] 
['a1', 'b2', 'c3', 'd4', 'e5', '6', '7'] 
>>> print '\n'.join([(x if x != None else '') + str(y) for (x,y) in izip_longest(L1,L2)]) 
a1 
b2 
c3 
d4 
e5 
6 
7