Home > other >  How to convert a list of list of strings into integers
How to convert a list of list of strings into integers

Time:12-07

This is a list that I have [['1.0\n'],['2.0\n'],['3.0\n']] and I would like to convert them into integers 1 2 3 without comma separation and \n.

I'm not sure how to do this conversion as there's a list within a list and I don't really know how to get rid of \n altogether. Thanks.

CodePudding user response:

# Sample list of list of strings
lst = [['1.0\n'], ['2.0\n'], ['3.0\n']]

# Convert the list of list of strings into a list of integers
result = []
for sublist in lst:
    for string in sublist:
        # Convert the string into a floating-point number, then into an integer
        result.append(f"{int(float(string.strip()))}")
        
# result: [1, 2, 3]
final_output = ' '.join(result)

# final_output: "1 2 3"
print(final_output)  

CodePudding user response:

if you want [[1], [2], [3]], you can try

lst = [['1.0\n'],['2.0\n'],['3.0\n']]
res = [[int(float(j.replace("\n", ""))) for j in i] for i in lst]

if you want [1, 2, 3], you can try

lst = [['1.0\n'],['2.0\n'],['3.0\n']]
res = [int(float(i[0].replace("\n", ""))) for i in lst]

CodePudding user response:

Depends on whether you want rounding or not and or a new list. Is there a reason why you have a list in a list? But you'd do something like this

x = [['1.0\n'],['2.0\n']]
y = [] 

for item in x:
    tmp = item[0].replace('\n','')
    y.append(int(float(tmp)))

print(y)

CodePudding user response:

There is a way:

ls=[['1.0\n'],['2.0\n'],['3.0\n']]
result=[]
for ll in ls:
    [result.append(int(float(l.replace('\n','')))) for l in ll]
print(result)

Output: [1, 2, 3]

This code just works under this condition: [if every element in the list has \n]

Like Raya's answer, I use the int(float(l)) way, if every element has '.0', you can also use l.replace('\n','').replace('.0','').

CodePudding user response:

Removing /n and consolidate to a single list

You could solve this with list comprehension.

list = [['1.0\n'], ['2.0\n'], ['3.0\n']]

my_list = [int(float(value[0].strip())) for value in list]

print(my_list)

Output: [1, 2, 3]

The main things to note in this solution are:

  • The nested lists are iterated through, selecting the first element of each with value[0].
  • Each iteration:
    • Value: '1.0\n' is stripped of the \n with value[0].strip()
    • Value: 1.0 is then converted to a float float(value[0].strip())
    • Value: 1 is then converted to a integer int(float(value[0].strip()))

Without comma separation

list = [['1.0\n'], ['2.0\n'], ['3.0\n']]

my_list = [int(float(value[0].strip())) for value in list]

my_string = " ".join(str(value) for value in my_list)

print(my_string)

Output: 1 2 3

  • Related