我有一个元组列表,通过电影和联合演员将一个演员与其他演员联系起来:
对于一个给定的演员E ActE:
conn_list = [('m6', 'D ActD'), ('m3', 'B ActB'), ('m2', 'Kevin Bacon')]
所以这说:
E ActE was in a movie m6 with D ActD
D ActE was in a movie m3 with B ActB
B ActB was in a movie m3 with Kevin Bacon
我只是想知道如何打印出来。我知道如何切换列表并从元组中获取元素。我正在使用for循环来迭代,但我不知道如何在打印字符串时处理不断变化的演员。
for connection in conn_list:
print '%s was in %s with %s'( , connection[0], )
这几乎是我坚持的地方。我不想制作多个印刷语句,因为电影和演员可能太多了。有什么想法吗?
答案 0 :(得分:1)
您的输入与您的格式字符串不匹配,但这是您要执行的操作:
actor_name = "ActE"
conn_list = [('m6', 'D ActD'),
('m3', 'B ActB'),
('m2', 'Kevin Bacon')]
for con in conn_list:
print "%s was in movie %s with %s" % (actor_name, con[0], con[1])
格式字符串将使用元组并将%s
替换为该位置的元素,例如:
"%s likes %s" % ("bob", "apples")
将第一个%s
替换为tuple[0]
,第二个%s
替换为tuple[1]
答案 1 :(得分:1)
我认为我们错过了一些上下文信息?如果conn_list
是演员E ActE
的连接列表,那么可能会有一个包含字符串E ActE
的变量。那是对的吗?
Serdalis指出了如何使用%
运算符打印所需的邮件,但如果您不想修改conn_list
的结构,那么您可以使用类似的内容这样:
current_actor = 'E ActE'
for connection in conn_list:
print '%s was in %s with %s' % (current_actor, connection[0], connection[1])
current_actor = connection[1]
当我使用conn_list
运行时,我得到:
E ActE was in m6 with D ActD
D ActD was in m3 with B ActB
B ActB was in m2 with Kevin Bacon
更好的方法是使用format(...)
字符串方法,因为%
运算符正在逐步淘汰:
current_actor = 'E ActE'
print connection in conn_list:
print '{0} was in {1} with {2}'.format(current_actor, connection[0], connection[1])
current_actor = connection[1]
产生相同的输出。
编辑:Serdalis在我写这篇文章时编辑了他们的解决方案。该解决方案现在使用conn_list
的原始形式。