簡體   English   中英

如何在python中將數字和列表拆分為子列表

[英]How to split number and list into sublist in python

我有一個變量num ,列表上有一堆數字

num = [1273849173948576379, 7483946582903647829]

如何將其拆分為兩個單獨的數字和子列表,如下所示:

[[12,73,84..],[74,83,94..]]

一種解決方案是

[[int(str(j)[i:i+2]) for i in range(0, len(str(j)), 2)] for j in num]

使用re做相同事情的另一種方法是:

num = [1273849173948576379, 7483946582903647829]
import re
print([list(map(int, re.findall('..?', str(x)))) for x in num])

列表理解方法會更有效,但是簡單的方法是:

num = [1273849173948576379, 7483946582903647829]
new_list = []

for number in num:
    # Converting each number into string so that we can slice using index
    str_number = str(number)

    # Empty list for storing pieces of each number in num 
    tmp = []

    # Using for loop to increment from start i.e. 0 till < length of string 
    # and each time increment is by 2
    for i in range(0, len(str_number), 2):

        # Slicing the index to get two digit number and appending to tmp
        int_number = str_number[i:i+2]
        tmp.append(int(int_number))

    # Finally done with one of the number in num so, appending to new_list
    new_list.append(tmp)

new_list

輸出:

[[12, 73, 84, 91, 73, 94, 85, 76, 37, 9],
 [74, 83, 94, 65, 82, 90, 36, 47, 82, 9]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM