【问题标题】:Question about printing multiple items in a list in a specific order in Python关于在 Python 中以特定顺序打印列表中的多个项目的问题
【发布时间】:2020-03-04 16:36:06
【问题描述】:

所以我已经为此绞尽脑汁了一段时间,并决定联系你们这些优秀的人。我试图弄清楚的问题是如何以特定顺序打印列表中的项目。我有一个清单:

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”语句只返回一个“无”值,这就是为什么我没有得到我想要的结果。谁能给我一些见解?任何帮助将不胜感激。提前致谢。

【问题讨论】:

  • 您似乎已经知道如何以所需的顺序打印元素(如动物名称所示)。您的问题是您将元素包装到生成器中 - 为什么要这样做?你认为str(x for x in m[4:]) 是什么意思?另外,您有什么理由将动物和声音存储在m 中,而不是将它们分成两个列表或使用dict 从动物映射到声音?
  • 宫城先生您好。在这种情况下,我对生成器的理解是有限的......因此我接触了社区。我没有创建两个列表的原因是因为我想看看如何在特定的列表中打印元素命令。我在 'm[]' 中使用这些词的唯一原因是因为它们对人们有意义。我很感激和反馈。谢谢。

标签: python list for-loop


【解决方案1】:

您可以通过列表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}')

【讨论】:

  • 爱这个奥斯汀!我以前从未使用过“zip”,所以我会努力了解更多。非常感谢!
  • 有了{},你可以让它像英语一样可读。例如:f'The {animal} goes {cry}'
【解决方案2】:

表达式(x for x in m[4:])被称为生成器表达式,是一个可以生成东西的对象,可能不是你真正想要的。

这将解决您的问题:

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

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

【讨论】:

    【解决方案3】:

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

    例如将您的列表分成两个列表,然后将它们压缩成一对列表

    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”更惯用了

    【讨论】:

      【解决方案4】:

      编码很好,但是通过将其分成两部分来使用通用设计:

      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]}")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-04
        • 1970-01-01
        • 1970-01-01
        • 2014-01-03
        • 1970-01-01
        • 2023-01-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多