列表只包含第二对元素

我是 python 的新手,所以我正在做一些实验,但我现在有一个小问题。

我有一个包含n 个数字的列表,我想创建一个新列表,其中只包含每对第二对 数字。

所以基本上如果我有这样的清单

oldlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

那么我希望新列表看起来像这样

newlist = [3, 4, 7, 8]

我已经尝试过该slice()功能,但我没有找到任何方法可以将我的列表分成两部分。然后我想我可以使用两个slice()以四为单位移动并以一为单位移动的函数,但是如果我合并这两个新列表,它们的顺序将不正确。

回答

如果您枚举列表,您将采用那些索引为 2 或 3 作为除以 4 的余数的条目:

>>> [val for j, val in enumerate(old_list) if j % 4 in (2, 3)]

[3, 4, 7, 8]

  • I might suggest `if ((j // 2) % 2) == 1` where now the first `2` is the size of the grouping, the second `2` is the interval of groups, and `1` is the index to select from the interval. `if ((j // size) % interval) == index` This allows you to parameterize the group size and index. E.g. for `if ((j // 3) % 2) == 0` you can get groups sized 3, with an interval of 2 groups and take the first index, `[1, 2, 3, 7, 8, 9]`.
  • @flakes big +1 to the suggestion! Can I include your suggestion in my [answer](https://stackoverflow.com/a/68122252/3896008) as well? Also, not sure if I should delete my answer because Mustafa's answer does the same thing but is more pythonic since no explicit indexing is used in this answer.

回答

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = [a[i]  for i in range(len(a)) if i%4 in (2,3)]

# Output: b = [3, 4, 7, 8]

在这里,我们使用第 3、第 4、第 7、第 8 次……等等的想法。索引除以 4 时的余数为 2 或 3。


回答

first_part = oldList[2::4] # every 4th item, starting from the 3rd item
second_part = oldList[3::4] # every 4th item starting from the 4th item

pairs = zip(first_part, second_part)
final_result = chain.from_iterable(pairs)


以上是列表只包含第二对元素的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>