简体   繁体   English

如何将单个元素连接到Python中的字符串列表

[英]How do I join individual elements into a list of strings in Python

I have a list of lists, say y = [[2, 4, 6, 7], [9, 0, 8, 12], [1, 11, 10, 5]] I want to convert each of the inner lists into a strings separated by '/' and output a list of the individual strings. 我有一个列表列表,例如y = [[2, 4, 6, 7], [9, 0, 8, 12], [1, 11, 10, 5]]我想转换每个内部列表转换为以'/'分隔的字符串,并输出各个字符串的列表。 How can I do this in python? 如何在python中做到这一点?

You could use str. 您可以使用str。 join after mapping the ints to strings within a list comprehension : 将int 映射列表理解内的字符串后加入

>>> y = [[2, 4, 6, 7], [9, 0, 8, 12], [1, 11, 10, 5]]
>>> formatted_y = ['/'.join(map(str, inner_list)) for inner_list in y]
>>> formatted_y
['2/4/6/7', '9/0/8/12', '1/11/10/5']

Or if you prefer you could use a couple of nested list comprehensions: 或者,如果您愿意,可以使用几个嵌套列表推导:

>>> formatted_y = ['/'.join(str(x) for x in inner_list) for inner_list in y]
>>> formatted_y
['2/4/6/7', '9/0/8/12', '1/11/10/5']

To go back to the original you can use str. 要返回原始版本,可以使用str。 split within a list compression: 在列表压缩中拆分

>>> original_y = [list(map(int, inner_str.split('/'))) for inner_str in formatted_y]
>>> original_y
[[2, 4, 6, 7], [9, 0, 8, 12], [1, 11, 10, 5]]
y = [[2, 4, 6, 7], [9, 0, 8, 12], [1, 11, 10, 5]]
myNewList = []
for myList in y:
    myMap = map(str,myList)

map (function, iterable) is used to apply a function (' str ' in this case) to all elements of a specified iterable (' myList '). map (函数,可迭代)用于将函数(在这种情况下为“ str ”)应用于指定的可迭代(“ myList ”)的所有元素。

    myString = '/'.join(myMap)

join (iterable) returns a string which is the concatenation of the strings in iterable. join (可迭代)返回一个字符串,该字符串是可迭代字符串的串联。 The separator between elements is the string providing this method. 元素之间的分隔符是提供此方法的字符串。

    myNewList.append(myString)

list. 名单。 append (elem) appends an element to the end of the list. append (elem)将元素追加到列表的末尾。

print(myNewList)

['2/4/6/7', '9/0/8/12', '1/11/10/5'] ['2/4/6/7','9/0/8/12','1/11/10/5']

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

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