簡體   English   中英

從五個項目列表中打印除第四項以外的所有內容,以便兩個列表彼此相鄰

[英]Print all except the fourth item from a five item list for two lists next to each other Python

所以我遇到的這個新問題就是這個。 我有兩個清單,每個清單有五個項目。

listone = ['water', 'wind', 'earth', 'fire', 'ice']
listtwo = ['one', 'two', 'three', 'four', 'five']

我想做的是將這些列表中的每個列表的第一,第二,第三和第五項打印成字符串:

print("the number is %s the element is %s" % (listtwo, listone)

但是它們每次都需要在新行中打印,以便針對兩個列表中的每個元素運行文本:

the number is one the element is water
the number is two the element is wind
the number is three the element is earth
the number is five the element is five

我不知道該怎么做。 我嘗試使用列表拆分,但由於它是五分之四中的第四項,所以我不知道如何跳過它。 我也用它在新行中列出字符串:

for x in listone and listtwo:
print("the number is {0} the element is {0}".format(x)  

但是我不知道如何將它與兩個列表一起使用,甚至不可以與兩個列表一起使用。

請幫忙 :(

編輯:

而且我也不知道腳本的元素是什么,所以我只能在列表中使用它們的編號。 因此,我需要在兩個列表中都刪除[4]。

for (i, (x1, x2)) in enumerate(zip(listone,listtwo)):
    if i != 3:
        print "The number is {0} the element is {1}".format(x1, x2)

說明

  • zip(listone,listtwo)給您一個元組列表(listone[0],listtwo[0]), (listone[1],listtwo[1])...
  • enumerate(listone)為您提供元組列表(0, listone[0]), (1, listone[1]), ...]

    (您猜對了,這是另一種更有效的zip(range(len(listone)),listone)

  • 通過將兩者結合起來,您可以獲得沿其索引想要的元素的列表
  • 因為您的第一個元素的索引為0 ,並且您不希望第四個元素,所以只需檢查索引是否為3
for pos in len(listone):
    if(pos != 3):
        print("the number is {0} the element is {1}".format(pos,listone[pos]))
for x in zip(list1,list2)[:-1]:
    print("the number is {0} the element is {0}".format(x))
listone = ['water', 'wind', 'earth', 'fire', 'ice']
listtwo = ['one', 'two', 'three', 'four', 'five']
z = zip(listone, listtwo)
z1 = z[:3]
z1.append(z[4])
for i, j in z1:
    print "the number is {} the element is {}".format(j, i)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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