I want to change the tuple value to the intro value, but I have a question.

Asked 2 years ago, Updated 2 years ago, 16 views

a = [('2019-05-01',),('2019-05-02',)...(n)] #sqlitedatetupleb value to be modified
b = ((2019, 5, 1), (2019, 5, 2)...(n)) #Calendar date tuple fixed value not changed
for i in range(len(a)):
    print(''.join(a[i]).replace('-', ','))

There are a,b values above, and you want to make the value a the same as the value b. The problem is that if you output a value above,

2019,05,01
2019,05,02

It comes out, but if I erase the value of 0 per month and day with 'replace', the value of 0 per year is erased, so I tried to erase it using the regular expression and make it into a tuple, so I couldn't tie it with inttuple So what I thought was to make it a = year, month, and day by giving three separate variables, but this doesn't work well, and I want to get help from other good methods.

python

2022-09-21 16:28

2 Answers

a = [('2019-05-01',),('2019-05-02',),('2019-05-03',)]
b = []

for i in range(len(a)):
    temp = a[i][0].split("-")
    temp[1] = str(int(temp[1]))
    temp[2] = str(int(temp[2]))

    b = b + [(", ".join(temp),)]

print(b)

>>> 
======= ======= RESTART: C:/Users/USER/Desktop/aaa.py =======
[('2019, 5, 1',), ('2019, 5, 2',), ('2019, 5, 3',)]


2022-09-21 16:28

You can transform one by one like the top, but Python keeps the code simpler if you think of it as a collection, that is, as a lump and program it.

d1 = '2019-05-01'
y, m, d = map(int, d1.split('-')) # Date of year int Type transformation and place it in the variable
triple(map(int, d1.split('-')) # Int-type conversion result is generated as a triple immediately

Chain (*a) is a platten treatment by peeling off the tuple of a.

In [19]: a = [('2019-05-01',), ('2019-05-02',)]

In [20]: list(chain(*a))                                                        
Out[20]: ['2019-05-01', '2019-05-02']

Finally, you can fill it out as below.

In [43]: from itertools import chain

In [44]: a = [('2019-05-01',), ('2019-05-02',)]                                 

In [45]: b = tuple(tuple(map(int, item.split('-'))) for item in chain(*a))      

In [46]: b                                                                      
Out[46]: ((2019, 5, 1), (2019, 5, 2))

In [47]: [tuple(map(int, item.split('-'))) for item in chain(*d)]               
Out[47]: [(2019, 5, 1), (2019, 5, 2)]


2022-09-21 16:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.