Home > Blockchain >  Adding a variable copying the one before and the one after for a long list
Adding a variable copying the one before and the one after for a long list

Time:06-16

I have 2 different lists that I would like to modify: The first one goes like so :

['chelsea','manchester','london','liverpool',..]

The list is quite long and goes on for a while. I would like to get it like so :

['chelsea','chelsea-manchester','manchester','london','london-liverpool','liverpool',...] 

and so on.

The second one is one with lots of numbers in

 ['10','11','12','13','14','15','16','17','18','19','20','21'..] 

which also goes on for a long time. I want to modify the list to get rid of the 4th and 5th variables for each block of 5 variables like so :

['10','11','12','15','16','17','20','21','22'] 

Many thanks,

CodePudding user response:

This is what you are looking for according to your post.

1st List

data = ['chelsea','manchester','london','liverpool']
new_data = [[data[i*2],f'{data[i*2]}-{data[i*2 1]}',data[i*2 1]] for i in range(int(len(data)/2))]
sum(new_data,[])

['chelsea', 'chelsea-manchester', 'manchester', 'london', 'london-liverpool', 'liverpool']

2nd List

number = ['10','11','12','13','14','15','16','17','18','19','20','21','22']
number = [int(i) for i in number]

new_number = [number[i:i 3] for i in range(0,len(number),5)]
sum(new_number,[])

[10, 11, 12, 15, 16, 17, 20, 21, 22]

CodePudding user response:

data = ['chelsea','manchester','london','liverpool']
data_connect = [[data[0]]]   [[f"{data[i-1]}-{data[i]}", data[i]] for i, x in enumerate(data[1:])]
data_rs = [y for x in data_connect for y in x]
data = ['10','11','12','13','14','15','16','17','18','19','20','21']
# split data(list) as length 5
data_split = [data[i:i   length] for i in range(0, len(data), 5)]
# remove 4th and 5th index value from each list
data_rs = [x for d in data_split for x in d[:3]]
  • Related