問題描述
假設我有一個這樣的 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']
使用
enumerate
獲取索引,每3rd個字母添加'x'
,eg:mod(n, 3) == 2
,然后拼接成字符串并list()
.
Use
enumerate
to get index, add'x'
every 3rd 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']
但是作為 @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 列表中的元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!