久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

在每個第 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 列表中的元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Why I cannot make an insert to Python list?(為什么我不能插入 Python 列表?)
Insert a column at the beginning (leftmost end) of a DataFrame(在 DataFrame 的開頭(最左端)插入一列)
Python psycopg2 not inserting into postgresql table(Python psycopg2 沒有插入到 postgresql 表中)
list extend() to index, inserting list elements not only to the end(list extend() 索引,不僅將列表元素插入到末尾)
How to add element in Python to the end of list using list.insert?(如何使用 list.insert 將 Python 中的元素添加到列表末尾?)
TypeError: #39;float#39; object is not subscriptable(TypeError:“浮動對象不可下標)
主站蜘蛛池模板: 宅男噜噜噜66一区二区 | 亚洲欧洲色| 国产一区二区福利 | 欧美精品在线观看视频 | 91蜜桃视频 | 欧美视频在线观看一区 | 国产视频一 | 欧美黄视频 | 在线观看国产小视频 | 日韩天堂av | 久久精品国产亚洲 | 狠狠干狠狠操 | 欧美不卡一区二区三区 | 欧美黄网站| 日韩成人在线播放 | 中文字幕精品在线观看 | 国产日本在线观看 | 福利一区二区 | 欧美精品在线观看视频 | 日韩一区二区三 | 日日摸天天添天天添破 | 日本三极片 | 第一福利视频导航 | 成人欧美一区二区三区白人 | 五月天网址| 精品国产aⅴ麻豆 | 日产精品久久久一区二区 | 色精品| 日韩中文字幕一区二区三区 | 一级特黄色片 | 天天操天天操 | 一本一道久久a久久精品蜜桃 | 在线观看日韩av | 国产一区精品在线观看 | 色婷婷亚洲 | 亚洲视频一区在线观看 | 欧洲一级片 | 亚洲天堂免费视频 | 一区二区精品 | 国产伦理一区二区 | 欧美一区二区三区在线播放 |