在每个第 n 个元素之后插入 Python 列表中的元素

Insert element in Python list after every nth element(在每个第 n 个元素之后插入 Python 列表中的元素)
本文介绍了在每个第 n 个元素之后插入 Python 列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

假设我有一个这样的 Python 列表:

Say I have a Python list like this:

letters = ['a','b','c','d','e','f','g','h','i','j']

我想在每个第 n 个元素之后插入一个x",比如说该列表中的三个字符.结果应该是:

I want to insert an 'x' after every nth element, let's say three characters in that list. The result should be:

letters = ['a','b','c','x','d','e','f','x','g','h','i','x','j']

我知道我可以通过循环和插入来做到这一点.我真正在寻找的是一种 Python 方式,也许是单线?

I understand that I can do that with looping and inserting. What I'm actually looking for is a Pythonish-way, a one-liner maybe?

推荐答案

我有两个一体机.

给定:

>>> letters = ['a','b','c','d','e','f','g','h','i','j']

  1. 使用enumerate获取索引,每3rd个字母添加'x'eg: mod(n, 3) == 2,然后拼接成字符串并list().

  1. Use enumerate to get index, add 'x' every 3rd letter, eg: mod(n, 3) == 2, then concatenate into string and list() it.

>>> list(''.join(l + 'x' * (n % 3 == 2) for n, l in enumerate(letters)))

['a', 'b', 'c', 'x', 'd', 'e', 'f', 'x', 'g', 'h', 'i', 'x', 'j']

但是作为 @sancho.s 指出如果任何元素有多个字母,这将不起作用.

But as @sancho.s points out this doesn't work if any of the elements have more than one letter.

使用嵌套推导来展平列表列表(a),以 3 个为一组进行切片,如果距离末尾小于 3,则添加 'x'列表.

Use nested comprehensions to flatten a list of lists(a), sliced in groups of 3 with 'x' added if less than 3 from end of list.

>>> [x for y in (letters[i:i+3] + ['x'] * (i < len(letters) - 2) for
     i in xrange(0, len(letters), 3)) for x in y]

['a', 'b', 'c', 'x', 'd', 'e', 'f', 'x', 'g', 'h', 'i', 'x', 'j']

(a) [item for subgroup in groups for item in subgroup] 展平一个锯齿状的列表列表.

(a) [item for subgroup in groups for item in subgroup] flattens a jagged list of lists.

这篇关于在每个第 n 个元素之后插入 Python 列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)