使用多个列表中的值进行Python字符串格式化

ofk*_*fko 1 python list string-formatting

我正在尝试使用多个列表中的值来格式化字符串.以下是伪代码,但应该给出预期输出的概念.输出将是每个列表中每个项目的组合:每个人都喜欢吃所有水果,同时做所有的爱好.那么如何在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}
Run Code Online (Sandbox Code Playgroud)

DSM*_*DSM 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}
Run Code Online (Sandbox Code Playgroud)

哪个产生

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
Run Code Online (Sandbox Code Playgroud)

或者您可以使用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}
Run Code Online (Sandbox Code Playgroud)