我正在尝试使用多个列表中的值来格式化字符串。以下是伪代码,但应该给出预期输出的概念。输出将是每个列表中每个项目的组合:每个人都喜欢在做所有爱好时吃掉所有水果。那么如何在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 :(得分:5)
如果我理解你的“输出将是每个列表中每个项目的组合:每个人在做每个爱好时都喜欢所有水果”系列,那么你需要一切可能的组合。您可以以嵌套循环方式执行此操作:
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}
答案 1 :(得分: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)
答案 2 :(得分: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