[英]Fastest way to find sub-lists of a fixed length, from a given list of values, whose elements sum equals a defined number
[英]How to create sub list with fixed length from given number of inputs or list in Python?
我想從Python中給定的輸入數量創建具有固定列表長度的子列表。
例如,我的輸入是: ['a','b','c',......'z']
...然后,我想將這些值放在幾個列表中。 每個列表的長度應為6。所以我想要這樣的東西:
first list = ['a','b','c','d','e','f']
second list = ['g','h','i','j','k','l']
last list = [' ',' ',' ',' ',' ','z' ]
我該如何實現?
這會將您的列表分為兩個等長(6)的列表:
>>> my_list = [1, 'ab', '', 'No', '', 'NULL', 2, 'bc', '','Yes' ,'' ,'Null']
>>> x = my_list[:len(my_list)//2]
>>> y = my_list[len(my_list)//2:]
>>> x
[1, 'ab', '', 'No', '', 'NULL']
>>> y
[2, 'bc', '', 'Yes', '', 'Null']
如果要將列表拆分為許多較小的列表,請使用:
chunks = [my_list[x:x+size] for x in range(0, len(my_list), size)]
其中size
是所需的較小列表的大小,例如:
>>> size = 2
>>> chunks = [my_list[x:x+size] for x in range(0, len(my_list), size)]
[[1, 'ab'], ['', 'No'], ['', 'NULL'], [2, 'bc'], ['', 'Yes'], ['', 'Null']]
>>> for item in chunks:
print (item)
[1, 'ab']
['', 'No']
['', 'NULL']
[2, 'bc']
['', 'Yes']
['', 'Null']
這將返回一個二維列表“ b”,其中每個列表包含的塊數與大塊一樣多。
a = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
b = []
chunksize = 6
def get_list(a, chunk):
return a[chunk*chunksize:chunk*chunksize+chunksize]
for i in range(int(len(a) / chunksize)):
b.append(get_list(a,i))
print(b)
輸出:
[['a', 'b', 'c', 'd', 'e', 'f'], ['g', 'h', 'i', 'j', 'k', 'l'], ['m', 'n', 'o', 'p', 'q', 'r'], ['s', 't', 'u', 'v', 'w', 'x']]
您的輸入是一個字符串,您需要先用逗號將其分割,然后再將其進一步分割:
input_string = "1, 'ab', '', 'No', '', 'NULL', 2, 'bc', '','Yes' ,'' ,'Null'"
bits = input_string.split(',')
x,y = bits[:6],bits[6:] # divide by 6
x,y = bits[:len(bits)//2],bits[len(bits)//2:] # divide in half
最小的解決方案:
x = ["a","b","c","d","e","f","g","h","i","j"]
size = 3 (user input)
for counter in range(0,len(x),size):
print(x[counter:counter+size])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.