繁体   English   中英

python - 将整数列表拆分为数字列表

[英]python - Splitting a list of integers into list of digits

我有一个包含8位整数的列表,其中每个整数代表一个标志。 例如:

qc = [11221427, 23414732, 144443277,...]

我想创建8个新变量,其中第一个变量是所有数字的第一个数字,依此类推。 例如:

qc1 = [1,2,1]
qc2 = [1,3,4]

我可以使用以下代码计算它:

qc_str = [str(e) for e in qc]

k,l = 0,0

for item in qc_str:
    qc1[k] = int(qc_str[k][l])
    qc2[k] = int(qc_str[k][l+1])
    qc3[k] = int(qc_str[k][l+2])
    qc4[k] = int(qc_str[k][l+3])
    qc5[k] = int(qc_str[k][l+4])
    qc6[k] = int(qc_str[k][l+5])
    qc7[k] = int(qc_str[k][l+6])
    qc8[k] = int(qc_str[k][l+7])

    k += 1

运行100,000行需要花费大量时间。 是否有更好或更快的方式。 任何想法将不胜感激。

这是一种方式:

qc = [11221427, 23414732, 144443277]

lst = [list(map(int, i)) for i in zip(*map(str, qc))]

# [[1, 2, 1],
#  [1, 3, 4],
#  [2, 4, 4],
#  [2, 1, 4],
#  [1, 4, 4],
#  [4, 7, 3],
#  [2, 3, 2],
#  [7, 2, 7]]

如果你真的需要这些作为单独的变量,可以使用lst[idx]或字典{i: j for i, j in enumerate(lst, 1)}

如果速度越快意味着处理时间越短,你应该注意到str()和int()强制转换在计算上非常昂贵。

您应该考虑使用整数除法和模数来提取单个数字:

k-th digit (from the left) = number / 10^(k-1) % 10

这里有一些快速的脏代码我用来证实我的假设。



    import time

    l = [x for x in range(1000000,9999999)]
    l2 = []
    l3 = []

    start = time.time()
    for x in l:
        a = str(x)
        l2.append(int(a[-2]))

    stop = time.time()
    print ("Elasped time: ", stop-start)

    start = time.time()
    for x in l:
        l3.append(x//10 % 10)

    stop = time.time()

    print("Elapsed time: ", stop-start)

基本上我比较执行str()和int()之间的时间,并使用整数除法提取数字以提取第二个数字。

我得到以下输出:

13.855608940124512
5.115100622177124

这是2.5倍的性能提升。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM