我用x元素迭代一个列表,对于每6个元素,im将这些元素存储到另一个变量(list1、list2、list3)中,但我的解决方案中最大的问题是,如果它不是6个元素,那么我的代码就排除了其余的元素,让我举一个例子:
假设我有一个从1到20开始的数组,当像我前面提到的那样将元素保存到list3变量时,它只会停止list3保存(13、14、15、16、17、18),所以列表的值应该如下:
list1:(1,2,3,4,5,6)
list2:(7,8,9,10,11,12)
list3:(13、14、15、16、17、18)
但是正确的值应该是
list1:(1,2,3,4,5,6,19,20)
list2:(7,8,9,10,11,12)
list3:(13、14、15、16、17、18)
我会让我在下面做的代码。
代码:
array = list(range(1, 100))
result = list(zip(* [iter(array)] * 6))
for item in result:
print(item)发布于 2021-08-14 22:47:44
array = range(1, 100)
result = [[], [], []]
for i, x in enumerate(array):
result[int(i / 6) % 3].append(x)
print(result)发布于 2021-08-14 22:54:28
我的解决方案不是特别的节奏曲,但它完成了你想要达到的目标:
守则:
foo = list(range(1, 100))
lists = []
temp = []
for i in foo:
temp.append(i)
if len(temp) == 6:
lists.append(temp)
temp = []
if len(temp) > 0:
lists[0] += temp
for list in lists:
print(list)产出为:
1、2、3、4、5、6、97、98、99 7、8、9、10、11、12 13、14、15、16、17、18 19、20、21、22、23、24、26、27、28、29、30 31、32、33、34、35、36 43、44、45、46、47、48 49、50、51、52、53、54 55、56、57、58、59、60 61、62、63、64、65、66 67、68、69、70、71、72、73、74、75、76、77、78 79、80、81、82、83、84 85、86、87、88、89、90 91、92、93、94、95、96
https://stackoverflow.com/questions/68787484
复制相似问题