如何将数组中的分隔元素拆分为其中包含分隔元素的新元素。
想法是要更改此
[ "Tiger Nixon, System Architect, Edinburgh, 5421, 2011/04/25", "Garrett Winters, Accountant, Tokyo, 422, 2011/07/25" ]
对此
[
[ "Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25" ],
[ "Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25"]
]
我尝试了此代码,但没有成功。我将my_string设置为顶部数组。
my_list = my_string.split(",")
答案 0 :(得分:4)
尝试一下:
# initial list
mystring = [ "Tiger Nixon, System Architect, Edinburgh, 5421, 2011/04/25", "Garrett Winters, Accountant, Tokyo, 422, 2011/07/25" ]
# empty list to store new values
array = []
# loop through the list and split each value
for i in mystring:
array.append(i.split(",")) # splits into list and appends it a new list
print(array) # prints the resultant array
您还可以使用以下一种划线员列表理解方法。
mystring = [string.split(",") for string in mystring]
输出:
[['Tiger Nixon', ' System Architect', ' Edinburgh', ' 5421', ' 2011/04/25'], ['Garrett Winters', ' Accountant', ' Tokyo', ' 422', ' 2011/07/25']]
查看实际使用的代码here。
答案 1 :(得分:4)
[i.split(',') for i in list_of_words]
输出:
[['Tiger Nixon', ' System Architect', ' Edinburgh', ' 5421', ' 2011/04/25'], ['Garrett Winters', ' Accountant', ' Tokyo', ' 422', ' 2011/07/25']]
我认为这有帮助!
答案 2 :(得分:2)
将list comprehension
与split()
一起使用
l = [ "Tiger Nixon, System Architect, Edinburgh, 5421, 2011/04/25", "Garrett Winters, Accountant, Tokyo, 422, 2011/07/25" ]
print([i.split(",") for i in l])
输出:
[['Tiger Nixon', ' System Architect', ' Edinburgh', ' 5421', ' 2011/04/25'],
['Garrett Winters', ' Accountant', ' Tokyo', ' 422', ' 2011/07/25']]