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 re开发者_运维技巧ally know how to get rid of \n altogether. Thanks.
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]
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)
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','')
.
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
withvalue[0].strip()
- Value:
1.0
is then converted to a floatfloat(value[0].strip())
- Value:
1
is then converted to a integerint(float(value[0].strip()))
- Value:
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
精彩评论