2017-08-25 49 views
0

我有一个名单,我希望把它的元素里面一个for循环的字符串是这样的:如何使用列表的索引做串插在一个for循环在python

my_list = ["Germany", "England", "Spain", "France"] 
for this in that: 
    do stuff 
    print(my_list[0]+ some other stuff) 

输出应该是像:

Germany + some other stuff 
England + some other stuff 
Spain + some other stuff 
France + some other stuff 

我怎么能回路串插指数呢?

谢谢!

编辑:循环有点不同。它更像这样:

for foo in bar: 
    another_bar = [] 
    for x, y in foo: 
     do stuff 
     a = object.method() 
     another_bar.append(my_list[0]+a) 

我需要将列表的字符串放入第二层嵌套循环。这里不能使用zip。

+0

据我所知这是你想要的东西:my_list = [“德国”,“英格兰”,“西班牙”,“法国”] 为国家my_list: 打印(国+“的一些其他的东西” ) –

+0

@ 0x1我编辑了您的修改以修复缩进。请确保它符合您的意图。另外,你的代码需要更多的结构。例如,'index'没有被定义。请参阅[MCVE]。 – Alexander

回答

2

我相信你认为thatmy_list的长度相同。如果是这样,您可以使用zip并行迭代两个容器。

my_list = ["Germany", "England", "Spain", "France"] 
my_other_list = [' is great at football', ' has good years in rugby', ' has Renaldo', ' is, well...'] 

def foo(bar): 
    return bar + '!' 

for country, bar in zip(my_list, my_other_list): 
    other = foo(bar) 
    print(country + other) 

# Output: 
# Germany is great at football! 
# England has good years in rugby! 
# Spain has Renaldo! 
# France is, well...! 
+0

它是一个嵌套循环。不幸的是我不能在这里使用zip。我编辑了这个问题。 – 0x1

0

您可以使用内置功能zip()zip允许并行处理每个列表:

创建一个迭代器,用于聚合来自每个迭代器的元素。

返回元组的迭代器,其中元组包含来自每个参数序列或迭代的第i个元素。当最短的输入迭代耗尽时,迭代器停止。使用单个迭代参数,它将返回1元组的迭代器。没有参数,它返回一个空的迭代器。

my_list = ["Germany", "England", "Spain", "France"] 
for country, this in zip(my_list, that): 
    # do stuff 
    print(country + that) 

如果您的列表大小不同,您可以使用itertoos.zip_longest

作出这样的聚合来自各个iterables的元素的迭代器。如果迭代的长度不均匀,缺少的值将用fillvalue填充。迭代继续下去,直到最长的迭代耗尽。

from itertools import zip_longest 

my_list = ["Germany", "England", "Spain", "France"] 
for country, this in zip_longest(my_list, that): 
    # do stuff 
    print(country + that) 
+0

它是一个嵌套循环。不幸的是我不能在这里使用zip。我编辑了这个问题。 – 0x1

0

我希望这可以帮助你。

for index, this in enumerate(that): 
    do stuff 
    print(my_list[index]+ some other stuff) 
+0

它是一个嵌套循环。不幸的是我不能在这里使用zip。我编辑了这个问题。 – 0x1

+0

你说你需要一个索引,而且我仍然认为枚举可以满足你。[enumerate](https://docs.python.org/2.7/library/functions.html?highlight=enumerate#enumerate) – hugoxia

相关问题