Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 打印字符串在元组列表中切换…帮助?_Python - Fatal编程技术网

Python 打印字符串在元组列表中切换…帮助?

Python 打印字符串在元组列表中切换…帮助?,python,Python,我有一个元组列表,通过电影和联合主演将给定演员与其他演员联系起来: 对于给定的演员或演员: 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 我只是想知道如何

我有一个元组列表,通过电影和联合主演将给定演员与其他演员联系起来:

对于给定的演员或演员:

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],            )

这正是我所处的困境。我不想发表多份书面声明,因为可能有太多的电影和演员。有什么想法吗?

您的输入与格式字符串不匹配,但这就是您要做的:

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
替换为
元组[0]
,第二个
%s
替换为
元组[1]



编辑:虽然这会解决你问题中的问题。。。再读几遍,我想你可能想要的是将同一部电影中的演员分组?但我不确定。

我想我们遗漏了一些上下文信息?如果
conn_list
是参与者
E ActE
的连接列表,那么可能有一个变量包含字符串
E ActE
。对吗

Serdalis已经指出了如何使用
%
操作符来打印所需的消息,但是如果不想修改
连接列表的结构,则可以使用如下内容:

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]
当我使用您的
连接列表运行此命令时,我得到:

E ActE was in m6 with D ActD
D ActD was in m3 with B ActB
B ActB was in m2 with Kevin Bacon
更好的方法是使用字符串的
格式(…)
方法,因为
%
运算符正在逐步淘汰:

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\u list

,那么您是否正在尝试将演员映射到电影?一个示例输出会很有帮助,我想我回答错了。当时我睡着了:(,你关于
.format
的说法是正确的,尽管这是so+1。