将元素数组更改为多个元素数组

2024-05-16 02:02:11 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将数组中分离的元素拆分为包含分离元素的新元素。你知道吗

我们的想法是改变这种状况

[ "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"]
]

我试过这个代码,但没用。我将\u字符串设置为顶部数组。你知道吗

my_list = my_string.split(",")

Tags: 代码元素my数组systemtigerarchitect状况
3条回答
[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 comprehensionsplit()一起使用

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']]

试试这个:

# 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。你知道吗

相关问题 更多 >