[英]Python grouping items and looping with a step
如果我有這個清單:
y =[a,b,c,d,e,f]
我想 select a
和b
,然后是e
和f
,它的語法是什么?
我試過了:
y = [a,b,c,d,e,f,g,h,i,j]
for letter in range(0,len(y),2):
print(letter)
我想要的結果是
[a, b, e, f i,j]
但相反,我每隔一秒收到一封信:
a
c
e
g
i
當我嘗試使用切片符號print(y[:1])時,我只得到列表中的前兩個值。
您需要將步驟設置為 4。對於每 4 個項目,您需要前兩個(跳過 3 和 4)。 所以:
lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
new_list = []
for i in range(0, len(lst), 4):
new_list.append(lst[i])
new_list.append(lst[i + 1])
print(new_list)
如果可迭代實際上只是一個字符串/字符集合:
from textwrap import wrap
from itertools import chain
print(list(chain.from_iterable(wrap("abcdefghij", 2)[::2])))
Output:
['a', 'b', 'e', 'f', 'i', 'j']
>>>
如果它是任意可迭代的:
from itertools import islice, chain
def chunk_wise(iterable, chunk_size):
it = iter(iterable)
while chunk := list(islice(it, chunk_size)):
yield chunk
print(list(chain.from_iterable(islice(chunk_wise("abcdefghij", 2), 0, None, 2))))
Output:
['a', 'b', 'e', 'f', 'i', 'j']
>>>
最直接的方法是使用帶有 if 子句(“過濾器”)的列表推導,它將選擇您想要的跨度中的項目。
ls = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
ls_spans = [x for i, x in enumerate(ls) if i % 4 in [0,1]]
為了更清楚地說明這一點,我們要做的是列表推導:
ls_spans = [x for x in ls] # Essentially just copies the list
但是我們希望 select 僅是“跨度”的某些成員,我們將其識別為 4 個單位長度:(我們列表中的abcd
、 efgh
、 ij
)。
ls_spans = [x for x in ls if x_is_wanted()]
為此,由於我們是否想要x
取決於它的 position,因此我們使用enumerate
將列表中的每個元素與索引配對(下面列表理解中的i
):
ls_spans = [x for i, x in enumerate(ls) if x_is_wanted(i)]
現在,我們考慮 function x_is_wanted
必須對每個元素說“是”或“否”( True
或False
):
def x_is_wanted(i: int) -> bool:
span_length = 4
acceptable_positions = [0, 1] # Remember we are 0-indexed!
return i % span_length in acceptable_positions # We use modulo to get the remainder, which is equivalent to the position in the span.
完整的程序可能如下所示:
def x_is_wanted(i: int) -> bool:
span_length = 4
acceptable_positions = [0, 1] # Remember we are 0-indexed!
return i % span_length in acceptable_positions
ls_spans = [x for i, x in enumerate(ls) if x_is_wanted(i)]
但如果我們不需要重用 function,我們可以更輕松地內聯它:
# Play with these params to see what changes!
span_length = 4
acceptable_positions = [0, 1]
ls = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
ls_spans = [x for i, x in enumerate(ls) if i % span_length in acceptable_positions]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.