久久久久久久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:“浮動對象不可下標)
主站蜘蛛池模板: 国产电影一区二区 | 久久国产综合 | 91xxx在线观看 | 综合视频在线 | 99精品一区二区 | 91精品国产91 | 中文字幕亚洲精品 | 日韩欧美在线一区二区 | 日韩h| 久久av网站 | 日韩精品免费视频 | 三级成人在线 | 福利社午夜影院 | 国产精品天堂 | 精国产品一区二区三区四季综 | 亚洲精品一区在线观看 | 欧美国产精品 | 国产精品一区二区在线 | 日韩欧美网 | 亚洲品质自拍视频 | 狠狠婷婷综合久久久久久妖精 | 中文字幕在线观看国产 | 亚洲欧洲激情 | 日本一本视频 | 精品视频一区二区三区在线观看 | 秋霞电影一区二区 | 精品日韩欧美一区二区 | 国产成人精品一区 | 欧美亚州综合 | 91影院在线观看 | 午夜久久久久久久久久一区二区 | 国产精品一区二区三区在线 | 99久久影院| 特a毛片 | 欧美网址在线观看 | av中文在线| 一区二区视频 | 国产视频1区| 97伦理电影 | 伊人热久久 | 日韩一区二区在线播放 |