关于在Python中按特定顺序打印列表中多个项目的问题

关于在Python中按特定顺序打印列表中多个项目的问题,python,list,for-loop,Python,List,For Loop,所以我绞尽脑汁想了一段时间,决定和你们这些优秀的人接触。我想解决的问题是如何按特定顺序打印列表中的项目。我有一份清单: m= ['dog','cat','horse','cow','woof','meow','neigh','moo'] 我希望我的结果如下所示: 'The dog goes woof' 'The cat goes meow' 'The horse goes neigh' 'The cow goes moo' 到目前为止,我已经尝试了以下代码: m= ['dog','cat',

所以我绞尽脑汁想了一段时间,决定和你们这些优秀的人接触。我想解决的问题是如何按特定顺序打印列表中的项目。我有一份清单:

m= ['dog','cat','horse','cow','woof','meow','neigh','moo']
我希望我的结果如下所示:

'The dog goes woof'
'The cat goes meow'
'The horse goes neigh'
'The cow goes moo'
到目前为止,我已经尝试了以下代码:

m= ['dog','cat','horse','cow','woof','meow','neigh','moo']

for i in m[:4]:
    print('The ' + i + ' goes ' + str(x for x in m[4:]))
我的结果是:

'The dog goes <generator object <genexpr> at 0x01177C70>'
'The cat goes <generator object <genexpr> at 0x01177C70>'
'The horse goes <generator object <genexpr> at 0x01177C70>'
'The cow goes <generator object <genexpr> at 0x01177C70>'
“狗走了”
“猫走了”
“马跑了”
“牛走了”

现在我发现'x'语句只返回一个'None'值,这就是为什么我没有得到想要的结果。有人能给我一些见解吗?任何帮助都将不胜感激。提前感谢。

您可以通过以下列表
zip

m = ['dog','cat','horse','cow','woof','meow','neigh','moo']

for x, y in zip(m, m[4:]):
    print(f'The {x} goes {y}')

# The dog goes woof
# The cat goes meow
# The horse goes neigh
# The cow goes moo
对于任何长度列表,您都可以执行以下操作:

for x, y in zip(m, m[len(m)//2:]):
    print(f'The {x} goes {y}')
表达式
(m[4:]中x代表x)
称为生成器表达式,它是一个可以生成东西的对象,可能不是您真正想要的东西

这将解决您的问题:

m = ['dog','cat','horse','cow','woof','meow','neigh','moo']

for i in range(4):
    print('The ' + m[i] + ' goes ' + m[i + 4])

列表或数组的概念通常是保存同质数据——如果你有动物名称和动物噪音,它们是不同的,数据结构应该区分它们

e、 把你的列表分成两个列表,然后把它们压缩成一个成对的列表

m= ['dog','cat','horse','cow','woof','meow','neigh','moo']
for pair in zip(m[:4], m[4:]):
  print(f"the {pair[0]} goes {pair[1]}")

尽管奥斯汀下面的“for x,y”更为惯用

但Harcoding很好,但还是采用了通用设计,将其分为两部分:

m= ['dog','cat','horse','cow','woof','meow','neigh','moo']
for pair in zip(m[:len(m)/2], m[len(m)/2:]):
  print(f"the {pair[0]} goes {pair[1]}")

似乎您已经知道如何按所需顺序打印元素(如动物名称所示)。您的问题是将元素包装到生成器中—为什么要这样做?你认为str(m[4:]中x代表x)是什么意思?还有,你为什么要将动物和声音存储在
m
中,而不是将它们分成两个列表,或者使用
dict
从动物映射到声音?嗨,Mistermiagi。在这种情况下,我对发电机的理解是有限的。。。我之所以没有创建两个列表,是因为我想知道如何以特定的顺序打印列表中的元素。我之所以在“m[]”中使用这些词,唯一的原因是它们对人们来说很有意义。我感谢你的支持和反馈。谢谢。我喜欢这个奥斯汀!我以前从未使用过“zip”,所以我会努力学习更多关于它的知识。非常感谢!有了这些
{}
你可以让它像英语一样可读。例如:
f'The{animal}goes{cry}'