I have a list which contains 8-digit integers, where each integer represents a flag. eg:
qc = [11221427, 23414732, 144443277,...]
I want to create 8 new variables where first variable is the first digit of all the numbers and so on. eg:
qc1 = [1,2,1]
qc2 = [1,3,4]
I am able to calculate it using the following code:
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
It takes a lot of time for running on 100,000 rows. Is there a better or faster way of doing it. Any thoughts would be appreciated.
This is one way:
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]]
If you really need these as separate variables, either use lst[idx]
or a dictionary {i: j for i, j in enumerate(lst, 1)}
.
If by faster you meant a lower processing time, you should note that the str() and int() casts are computationally pretty expensive.
You should consider using integer division and modulus to extract the single digits:
k-th digit (from the left) = number / 10^(k-1) % 10
Here some quick dirty code I used to confirm my hypothesis.
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)
Basically I compare the timings between doing a str() and an int() and extracting the digits using integer division to extract the 2nd digits.
I get the following output:
13.855608940124512
5.115100622177124
That's a 2.5x performance boost.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.