2017-08-25 117 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

相關問題