Home > Mobile >  adding the same number to a list if first element is same python list
adding the same number to a list if first element is same python list

Time:02-15

I have lists of data and I want to add the same number to every list if the first element of list is same.

for i in range(1,len(file_list)):
    myfiles = open(file_list[i], 'r')
    reader = csv.reader(myfiles)
    allRows = [row for row in reader][1:]

sample_list = [['FFC-CJUN', 'D', '20090521', '000000', '95.3600', '95.3600', '95.3600', 
'95.3600', '1000', '0'] ['FFC-CJUN', 'D', '20090521', '000000', '95.3600', '95.3600', '95.3600', 
'95.3600', '1000', '0']['FFC-CJUNW1', 'D', '20100624', '000000', '98.1400', '98.1400', '98.1400', 
'105.1300', '1', '0']['FFC-CJUNW1', 'D', '20100624', '000000', '98.1400', '98.1400', '98.1400', 
'105.1300', '1', '0']]

I want to add same number at the end of list and my actual data should look like

actual_list1 = [['FFC-CJUN', 'D', '20090521', '000000', '95.3600', '95.3600', '95.3600', 
'95.3600', '1000', '0', '1'] ['FFC-CJUN', 'D', '20090521', '000000', '95.3600', '95.3600', '95.3600', 
'95.3600', '1000', '0', '1']['FFC-CJUNW1', 'D', '20100624', '000000', '98.1400', '98.1400', '98.1400', 
'105.1300', '1', '0', '2']['FFC-CJUNW1', 'D', '20100624', '000000', '98.1400', '98.1400', '98.1400', 
'105.1300', '1', '0', '2']]

Any help Please.

CodePudding user response:

Simply use another list ('idx' in my example) to store already-exist 'first element', then assign group number by .index() to get index number of 'first element' in the list

sample_list1 = ['FFC-CJUN', 'D', '20090521', '000000', '95.3600', '95.3600', '95.3600', '95.3600', '1000', '0']
sample_list2 = ['FFC-CJUN', 'D', '20090521', '000000', '95.3600', '95.3600', '95.3600', '95.3600', '1000', '0']
sample_list3 = ['FFC-CJUNW1', 'D', '20100624', '000000', '98.1400', '98.1400', '98.1400', '105.1300', '1', '0']
sample_list4 = ['FFC-CJUNW1', 'D', '20100624', '000000', '98.1400', '98.1400', '98.1400', '105.1300', '1', '0']

lists = [sample_list1, sample_list2, sample_list3, sample_list4]
idx = []
for l in lists:
    if l[0] not in idx:
        idx.append(l[0])
    l.append(f"{idx.index(l[0])}")
    print(l)

Result:

['FFC-CJUN', 'D', '20090521', '000000', '95.3600', '95.3600', '95.3600', '95.3600', '1000', '0', '0']
['FFC-CJUN', 'D', '20090521', '000000', '95.3600', '95.3600', '95.3600', '95.3600', '1000', '0', '0']
['FFC-CJUNW1', 'D', '20100624', '000000', '98.1400', '98.1400', '98.1400', '105.1300', '1', '0', '1']
['FFC-CJUNW1', 'D', '20100624', '000000', '98.1400', '98.1400', '98.1400', '105.1300', '1', '0', '1']
  • Related