2012-01-31 65 views
1

我試圖使用多個列表中的值來格式化字符串。以下是僞代碼,但應該給出預期輸出的概念。輸出將是每個列表中每個項目的組合:每個人都喜歡吃所有水果,同時做所有業餘愛好。那麼如何在Python中做到這一點?Python字符串使用多個列表中的值格式化

應該有len(names)*len(fruits)*len(hobbies)可能性(64在我的例子)

names = ['tom','marry','jessica','john'] 
fruits = ['oranges','apples','grapes','bananas'] 
hobbies = ['dancing','sitting','bicycling','watching tv'] 

print '%(name)s likes to eat %(fruit)s while %(hobby)s \n' 
     % {'name':names, 'fruit':fruits, 'hobby':hobbies} 
+0

很多偉大的答案了:) – ofko 2012-01-31 04:23:40

回答

5

如果我理解了你的「輸出將會是co每個列表中每個項目的組合:每個人在做每個愛好時都喜歡所有的水果「行,你想要每種可能的組合。您可以在嵌套循環的方式做到這一點:

names = ['tom','mary','jessica','john'] 
fruits = ['oranges','apples','grapes','bananas'] 
hobbies = ['dancing','sitting','bicycling','watching tv'] 

for name in names: 
    for fruit in fruits: 
     for hobby in hobbies: 
      print '%(name)s likes to eat %(fruit)s while %(hobby)s' % {'name':name, 'fruit':fruit, 'hobby':hobby} 

產生

tom likes to eat oranges while dancing 
tom likes to eat oranges while sitting 
tom likes to eat oranges while bicycling 
tom likes to eat oranges while watching tv 
tom likes to eat apples while dancing 
[etc.] 
john likes to eat bananas while bicycling 
john likes to eat bananas while watching tv 

,或者您可以使用itertools模塊裏,其中有一個功能product,讓你的輸入列表中的每一個可能的組合:

import itertools 

for name, fruit, hobby in itertools.product(names, fruits, hobbies): 
    print '%(name)s likes to eat %(fruit)s while %(hobby)s' % {'name':name, 'fruit':fruit, 'hobby':hobby} 
+0

如果其中一個列表爲空(使用itertools)會發生什麼? – ofko 2012-01-31 05:06:19

+0

@ofko:與嵌套循環版本中的其中一個列表爲空的情況完全相同:無。如果你迭代一個空列表,你永遠不會進入內部代碼。 – DSM 2012-01-31 05:09:49

2

只需使用一個for循環:

names = ['tom','marry','jessica','john'] 
fruits = ['oranges','apples','grapes','bananas'] 
hobbies = ['dancing','sitting','bicycling','watching tv'] 

for name in names: 
    for fruit in fruits: 
     for hobby in hobbies: 
      print '%(name)s likes to eat %(fruit)s while %(hobby)s' \ 
        % {'name': name, 'fruit': fruit, 'hobby': hobby} 

但是,如果你問我,我總是覺得一切看起來更好地與.format()

for name in names: 
    for fruit in fruits: 
     for hobby in hobbies: 
      print '{} likes to eat {} while {}'.format(name, fruit, hobby) 
+0

請參閱我的編輯 – ofko 2012-01-31 04:16:37

+0

,我不認爲這是正確的 - 他希望所有可能的組合(4 * 4 * 4 = 64)。 – 2012-01-31 04:18:24

+0

@ofko我也編輯了我的答案 – juliomalegria 2012-01-31 04:20:02

2

itertools模塊提供product功能,其產生更多鈔票所有元組:

>>> from itertools import product 
>>> names = ['tom','marry','jessica','john'] 
>>> fruits = ['oranges','apples','grapes','bananas'] 
>>> hobbies = ['dancing','sitting','bicycling','watching tv'] 
>>> for n, f, h in product(names, fruits, hobbies): 
...  print '%s likes to eat %s while %s' % (n, f, h) 

你也可以直接使用的元組:

>>> for t in product(names, fruits, hobbies): 
...  print '%s likes to eat %s while %s' % t 
+0

第二個是如此簡潔,我愛蟒蛇! – ofko 2012-01-31 04:29:22