【问题标题】:Creating a list that gives a specific value at even indexes and another value at odd indexes创建一个列表,在偶数索引处给出特定值,在奇数索引处给出另一个值
【发布时间】:2018-07-21 21:19:21
【问题描述】:

我想创建一个列表,比如说 chelsea_fc,它将在偶数索引中填充值“EPL Champions”,在奇数索引中填充值“Manager Sacked”,直到给定范围。 (不想硬编码范围)

我对如何做到这一点感到困惑。请帮忙

【问题讨论】:

标签: python list indexing


【解决方案1】:

您可以这样做(或任何其他重复的列表),如下所示:

 chelsea_fc = ['Manager Sacked', 'EPL Champions']*(range_of_choice/2)
 print(chelsea_fc)

【讨论】:

  • 感谢 Nathan 的替代方案
【解决方案2】:

照你说的写出来!

>>> ['a' if i % 2 else 'b' for i in range(10)]
['b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a']

【讨论】:

  • 0 是偶数,为什么列表在索引 0 处给我 b?
  • @ArkaBose 因为0 % 20(如此均匀),但0 的计算结果为False,因此使用了else 选项。你可以做if i % 2 == 0 然后输出就是你想要的。或者你可以做if not i % 2,这只会翻转它们。或者你可以直接说'b' if i % 2 else 'a'。这取决于你!
  • 我的错,只是一个新手。谢谢
  • @ArkaBose 没问题
猜你喜欢
  • 2019-02-23
  • 2019-05-14
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-15
相关资源
最近更新 更多