问题描述
说我有这样的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']
-
使用
枚举
获取索引,添加'x'
每3个字母,例如:mod(n,3 )== 2
,然后连接成字符串和list()
它。
Use
enumerate
to get index, add'x'
every 3 letter, eg:mod(n, 3) == 2
, then concatenate into string andlist()
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']
但是作为 如果任何元素包含多个字母,则此方法无效。
But as @sancho.s points out this doesn't work if any of the elements have more than one letter.
使用嵌套式解析来展平列表列表,以3个为一组进行切片,其中'x'
在列表末尾少于3时添加。
Use nested comprehensions to flatten a list of lists, 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) [子组中项目的子组项目]
展平锯齿状的列表列表。
(a) [item for subgroup in groups for item in subgroup]
flattens a jagged list of lists.
这篇关于在每个第n个元素之后在Python列表中插入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!