[英]Changing Array of elements to multiple array of elements
如何將數組中的分隔元素拆分為其中包含分隔元素的新元素。
這個想法是改變這個
[ "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(",")
嘗試這個:
# 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
您還可以使用下面的一種 liner list comprehension 方法。
mystring = [string.split(",") for string in mystring]
輸出:
[['Tiger Nixon', ' System Architect', ' Edinburgh', ' 5421', ' 2011/04/25'], ['Garrett Winters', ' Accountant', ' Tokyo', ' 422', ' 2011/07/25']]
請參閱此處的操作代碼。
[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']]
我認為它有幫助!
將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']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.