簡體   English   中英

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

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM