2017-06-05 99 views
-2

說我有諸如獲取生成一個列表:如何根據變量自定義列表分組?

list_x = [0,1,2,3,4,5,6,7,8,9] 

然後我把它像這樣:

list_x = [01,23,45,67,89] 

與此列表理解:

list_x = [0,1,2,3,4,5,6,7,8,9] 
grp_count = 2 
new_list = map(int, [list_x[i+0]+list_x[i+1] for i in range(0, len(list_x)-1, grp_count)]) 

哪有我使這個代碼,所以我可以將它分組爲基於`grp_count'

例如,如果group_count = 5

list_x = [,56789] 

我知道我必須插入多個list_x[i+n]每次添加的分組大小的莫名其妙。

+0

你的代碼提供'1,5,9,13,17'。那是你需要的嗎? – Psidom

+0

默認情況下,Python不顯示整數的前導零。 – martineau

+1

什麼應該是列表中的returnformat:strings(python中的字符列表)? O元組? – inetphantom

回答

0

您可以使用list comprehension做這樣的例子的伎倆:

def grouper(a, num): 
    if num > int(len(a)/2): 
     return [] 
    # If you need to return only a list of lists use: 
    # return [a[k:k+num] for k in range(0, len(a), num)] 
    return ["".join(map(str, a[k:k+num])) for k in range(0, len(a), num)] 

a = [0,1,2,3,4,5,6,7,8,9] 
print(grouper(a, 2)) 
print(grouper(a, 5)) 

輸出:

['01', '23', '45', '67', '89'] 
['', '56789'] 
+0

返回的行非常易讀,總體易懂...不是 – inetphantom

+0

現在用'map()'?這是一個簡單的'list comprehension' ... –

+0

不客氣。格萊德這個答案正在幫助你。快樂的編碼。 –

1

這看起來很像迭代工具石斑魚食譜從https://docs.python.org/3/library/itertools.html

from itertools import zip_longest 

def grouper(iterable, n, fillvalue=None): 
    "Collect data into fixed-length chunks or blocks" 
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" 
    args = [iter(iterable)] * n 
    return zip_longest(*args, fillvalue=fillvalue) 

然後

list_x = [0,1,2,3,4,5,6,7,8,9] 
print(list(grouper(list_x, 5, 0))) 

[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)] 
1

正如我在評論說,沒有辦法建立在Python整數列表會顯示類似[,56789]因爲Python沒有用領​​秀整數的價值那樣的零。你可以得到最接近的是[1234, 56789]

但是您可以創建與他們這些數字像這樣的列表:

def grouper(n, iterable): 
    return zip(*[iter(iterable)]*n) 

list_x = [0,1,2,3,4,5,6,7,8,9] 
grp_count = 5 
new_list = [''.join(map(str, g)) for g in grouper(grp_count, list_x)] 
print(new_list) #-> ['', '56789'] 
+0

你能解釋爲什麼在'zip()'裏面使用'* [iter(iterable)] * n'?我沒有理解背後的原因。謝謝。 –

+1

@Chiheb:爲什麼?因爲,用作'zip()'的參數,所以這是一種緊湊的方式來創建一個迭代器,該迭代器將從'n'項目組的第二個參數中返回元素。那是你想知道的嗎?如果寫成'*([iter(iterable)] * n)',可能會更容易理解。 – martineau

+1

感謝您的評論。這是我第一次看到像你這樣的一段代碼。而且我認爲即使在你評論之後,我的表現也不盡如人意。我會試着冥想你的答案,並嘗試理解你用來解決當前問題的方式。非常感謝您的評論。祝你今天愉快。 –