简体   繁体   中英

Python List Conversion to string and split

Any Idea when I do the split on list( after converting to string) I am not getting the first and the last elements in the list....

if __name__ =="__main__":
    lst1= ['3 6 2 5'];
    lst1=str(lst1);
    a = [int(i) for i in lst1.split(' ') if i.isdigit()]
    print(a);

Outputs

[6, 2]

What I am looking for is

[2,3,5,6]

I think its due to the split characters which it finds after the 3(first element), but not sure how to resolve it.

When you convert lst1 to a string, you get

"['3 6 2 5']"

When you split this, you get the list: fir

["['3", "6", "2", "5']"]

"['3".isdigit() and "5']".isdigit() are false, so it doesn't print those elements.

To get the result you expect, you should not convert the list to a string. You should index the list to get its elements.

for s in lst1:
    a = [int(i) for i in s.split(' ') if i.isdigit()]
    print(a)

Try it.

lst1= ['3 6 2 5'];
a = [int(i) for i in lst1[0].split(' ') if i.isdigit()]
a.sort()
print(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM