![](/img/trans.png)
[英]How to split a list into sublists based on single elements of the initial list first and then contiguous portions of the list simply in python?
[英]Split single list elements
我有一個要處理的數據列表。
initial_list = [333322222111111, 555000033311123, 666333312466332]
我想將每個元素放到一個新列表中,然后將它們進一步拆分,這樣我的新列表將是:
new_list = [[333,22222111111], [555, 000033311123], [666,333312466332]]
我已經完成以下工作:
new_list = [[] for i in range(0, len(initial_list))]
這給了我: new_list = [[], [], []]
for i in range(0, len(new_list)):
new_list[i].append(initial_list[i])
這給了我
[[333322222111111], [555000033311123], [666333312466332]]
我現在陷入了如何拆分每個嵌套列表的問題。.split方法僅適用於字符串..每個列表中的前3個值都需要切除..理想情況下,我什至希望將其他部分拆分為甚至更大的塊
任何關於該走的方向的建議都是很棒的。
假設您所有的價值都一樣。 以下代碼將輸出您想要的內容。
>>> a = [333322222111111, 555000033311123, 666333312466332]
>>> [ [i/10**12, i%10**12] for i in a]
[[333, 322222111111], [555, 33311123], [666, 333312466332]]
有關答案的一些資源: 列表推導
嘗試這樣,只需使用字符串切片,
In [18]: print [map(int,[i[:3],i[3:]]) for i in map(str,initial_list)]
[[333, 322222111111], [555, 33311123], [666, 333312466332]]
initial_list = [333322222111111, 555000033311123, 666333312466332]
new_list =[]
for i in initial_list:
i=str(i)
new_list.append([int(i[0:3]),int(i[3:])])
print new_list
輸出:
[[333, 322222111111], [555, 33311123], [666, 333312466332]]
根據您的疑問(評論部分)以以下新格式獲取輸出:
output: [[333, 3222, 2211, 1111], [555, 0, 3331, 1123], [666, 3333, 1246, 6332]]
這是代碼:
initial_list = [333322222111111, 555000033311123, 666333312466332]
new_list =[]
for i in initial_list:
i=str(i)
temp_list=[]
temp_list.append(int(i[0:3]))
jump=4
for j in range(3,len(i),jump):
temp_list.append(int(i[j:j+jump]))
new_list.append(temp_list)
print new_list
這樣嘗試
a = [333322222111111, 555000033311123, 666333312466332]
mylst = [divmod(i,10**12) for i in a]
print mylst
輸出:
[[333, 322222111111], [555, 33311123],[666, 333312466332]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.