如何使用python中列表的索引在for循环中进行字符串插值

时间:2017-08-25 00:37:17

标签: python list for-loop indices string-interpolation

我有一个列表,我想把它的元素放在一个for循环字符串中,如下所示:

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。

3 个答案:

答案 0 :(得分: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...!

答案 1 :(得分:0)

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

  

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

     

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

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

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

  

创建一个聚合来自每个迭代的元素的迭代器。如果迭代的长度不均匀,则使用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)

答案 2 :(得分:0)

我希望这可以帮到你。

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