简体   繁体   中英

Python: How can I take a list of lists, convert every element into strings, and return the list of lists?

For example:

list = [[11,2,3,5],[5,3,74,1,90]]

returns the same thing, only everything is a str instead of an int. I want to be able to use .join on them. Thanks!

If you only ever go 2 lists deep:

>>> l = [[11, 2, 3, 5], [5, 3, 74, 1, 90]]
>>> [[str(j) for j in i] for i in l]
[['11', '2', '3', '5'], ['5', '3', '74', '1', '90']]

I'd use a list-comp and map for this one:

[ map(str,x) for x in lst ]

But I suppose py3.x would need an addition list in there (yuck).

[ list(map(str,x)) for x in lst ]

As a side note, you can't use join on this list we return anyway. I'm guessing you want to do something like this:

for x in lst:
   print ("".join(x))

If that's the case, you can forgo the conversion all together and just do it when you're joining:

for x in lst:
   print ("".join(str(item) for item in x))

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