简体   繁体   English

列表到字符串的转换

[英]List to String conversion

I have a list of lists like so: 我有一个像这样的清单清单:

list = [[10, 11, 12, 13][14, 15, 16, 17]]

I want to convert them to Strings but maintain the list organization 我想将它们转换为字符串,但维护列表组织

list = [["10", "11", "12", "13"]["14", "15", "16", "17"]]

How would I do that? 我该怎么做?

Try this, using nested list comprehensions and the str() built-in function to perform the actual conversion: 尝试使用嵌套列表推导和内置的str()函数执行实际的转换:

lst = [[10, 11, 12, 13], [14, 15, 16, 17]]
lst = [[str(x) for x in slst] for slst in lst]

Now lst will look as expected: 现在, lst将会看起来像预期的那样:

lst
=> [['10', '11', '12', '13'], ['14', '15', '16', '17']]

Also notice that it's a bad idea to name a variable list , that clashes with a built-in function name. 还要注意,给变量list命名是一个坏主意,它与内置函数名称冲突。 That's why I renamed it to lst . 这就是为什么我将其重命名为lst的原因。

list=[[10,11,12,13],[14,15,16,17]]
list=[map(str, list)for list in list]
print list

RESULT: [['10', '11', '12', '13'], ['14', '15', '16', '17']] 结果:[['10','11','12','13'],['14','15','16','17']]

First of all, I think that you forgot to place a comma between your two sublist. 首先,我认为您忘记在两个子列表之间放置逗号。

Secondly, do not use list as a variable name because you are shadowing the list data structure. 其次,不要将list用作变量名,因为您正在隐藏list数据结构。

Finally, you can solve it using the map function: 最后,您可以使用map函数解决此问题:

>>> lst = [[10, 11, 12, 13],[14, 15, 16, 17]]
>>> map(lambda x: map(str, x), lst)
[['10', '11', '12', '13'], ['14', '15', '16', '17']]
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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