[英]How to do string interpolation in a for loop using the indices of a list in python
我有一个列表,我想将其元素放入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。
我相信你的假设that
相同lenght为my_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...!
您可以使用内置函数zip()
。 zip
允许并行处理每个列表:
创建一个迭代器,以聚合每个可迭代对象中的元素。
返回一个元组的迭代器,其中第i个元组包含每个参数序列或可迭代对象中的第i个元素。 当最短的可迭代输入耗尽时,迭代器将停止。 使用单个可迭代参数,它将返回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)
希望对您有所帮助。
for index, this in enumerate(that):
do stuff
print(my_list[index]+ some other stuff)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.