Home > Blockchain >  How to replace multiple unsorted list elements at once in the simplest way?
How to replace multiple unsorted list elements at once in the simplest way?

Time:07-29

I would like to write the code below in the simplest way possible. It can be written better for sure. Such a record itches. How can I do it?

table_body_line_striped_typed = [float(argument) for argument in table_body_line_striped]
table_body_line_striped_typed[0] = int(table_body_line_striped_typed[0])
table_body_line_striped_typed[1] = int(table_body_line_striped_typed[1])
table_body_line_striped_typed[4] = int(table_body_line_striped_typed[4])
table_body_line_striped_typed[5] = int(table_body_line_striped_typed[5])
table_body_line_striped_typed[8] = int(table_body_line_striped_typed[8])

CodePudding user response:

I hope this is simple enough

table_body_line_striped_typed = [float(argument) for argument in table_b]
for index in [0,1,4,5,8]:
    table_body_line_striped_typed[index] = int(table_body_line_striped_typed[index])

you can also use this one-liner for the same result:

table_body_line_striped_typed = [float(arg) if i in [0,1,4,5,8] else int(arg) for i,arg in enumerate(table_b)] 

CodePudding user response:

if you know what indices should be ints, do an else in your list comprehension

table_b = [1, 2, 3.4, 5.6, 6, 7, 7.8, 8.6, 9]
int_indices = [0, 1, 4, 5, 8]
table_body_line_striped_typed = [
  float(argument) if i not in int_indices else int(argument) for i, argument in enumerate(table_b) 
]
for arg in table_body_line_striped_typed:
    print(f'{arg=}, type={type(arg)}')

output:

arg=1, type=<class 'int'>
arg=2, type=<class 'int'>
arg=3.4, type=<class 'float'>
arg=5.6, type=<class 'float'>
arg=6, type=<class 'int'>
arg=7, type=<class 'int'>
arg=7.8, type=<class 'float'>
arg=8.6, type=<class 'float'>
arg=9, type=<class 'int'>

if you don't know and want to convert all elements in the list depending on if it should be a float or not, the logic will depend on the type you're converting from.

for example, if you're converting from strings, check if there's a decimal, or if there are non zero digits after a decimal. if yes, it's a float. if no, an int

you can also use modulo 1 to check if the float is a round number, or use the floats .is_integer() method


table_body_line_striped_typed = [float(argument) for argument in table_b]
table_body_line_striped_typed = [int(arg) if arg.is_integer() else arg for arg in table_body_line_striped_typed ]


for arg in table_body_line_striped_typed:
    print(f'{arg=}, type={type(arg)}')

output:

arg=1, type=<class 'int'>
arg=2, type=<class 'int'>
arg=3.4, type=<class 'float'>
arg=5.6, type=<class 'float'>
arg=6, type=<class 'int'>
arg=7, type=<class 'int'>
arg=7.8, type=<class 'float'>
arg=8.6, type=<class 'float'>
arg=9, type=<class 'int'>
  • Related