从相邻的两个列表中打印除第四项以外的所有项

2024-05-15 03:32:18 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我遇到的新问题就是这个。我有两张单子,每个单子有五项。在

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

我要做的是将这些列表中的第一项、第二项、第三项和第五项打印成一个字符串:

^{pr2}$

但它们每次都需要在新行中打印,以便为两个列表中的每个元素运行文本:

^{3}$

我不知道怎么做。我试过使用列表分割,但由于它是五项中的第四项,所以我不知道如何跳过它。此外,我还使用此命令在新行中列出字符串:

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

但我不知道如何在两个列表中使用它,或者它是否可以用于两个列表。在

请帮忙:(

编辑:

而且我不知道脚本的元素是什么,所以我只能在列表中使用它们的编号。所以我需要在这两个列表中去掉[4]。在


Tags: the字符串元素列表isonefire单子
3条回答
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))

相关问题 更多 >

    热门问题