[英]how to get the list of the lists?
I have a problem like that: 我有这样的问题:
list = ['a1',['b1',2],['c1',2,3],['d1',2,3,4]]
I want to get a new list like that 我想得到一个像这样的新清单
new_list['a1','b1','c1','d1']
I do like this: 我喜欢这样:
lst = ['a1',['b1',2],['c1',2,3],['d1',2,3,4]]
for item in lst:
print(item)
result is: 结果是:
a1
['b1', 2]
['c1', 2, 3]
['d1', 2, 3, 4]
But I want the first element of each result 但是我想要每个结果的第一个元素
The best answer is like this : 最好的答案是这样的:
my_list = list()
lst = ['a1',['b1',2],['c1',2,3],['d1',2,3,4]]
for element in lst:
if type(element)==type('string'):
my_list.append(element)
else:
my_list.append(element[0])
print(my_list)
Thank you! 谢谢!
Do it as below: 如下进行:
>>> my_list = list()
>>> lst = ['a1',['b1',2],['c1',2,3],['d1',2,3,4]]
>>> for element in lst:
if type(element)==type('string'):
my_list.append(element)
else:
my_list.append(element[0])
It will produce: 它将产生:
>>> my_list
['a1', 'b1', 'c1', 'd1']
>>>
As you see above, first I created a list (named my_list
) and then checked each elements of your list. 如您在上方看到的,首先我创建了一个列表(名为
my_list
),然后检查了列表中的每个元素。 If the element was a string, I added it to my_list
and otherwise (ie it is a list) I added the first element of it to my_list
. 如果该元素是字符串,则将其添加到
my_list
,否则(即它是一个列表)将其第一个元素添加至my_list
。
I would do 我会做
res = []
for x in the_list:
if x is Array:
res.append(x[0])
else:
res.append(x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.