如何从列表中提取字符串

时间:2016-10-06 03:41:40

标签: python python-2.7 python-3.x

我是Python的新手,没有任何编程背景,除了一些shell脚本。

我想从下面的列表中提取2个字段:这里我想要'标题'和'播放'并将其分配给另一个列表,例如)new_list = [title,plays]

alist=[(0, 'title', 'TEXT', 0, None, 0), (1, 'plays', 'integer', 0, None, 0)]

2 个答案:

答案 0 :(得分:3)

最简单的方法当然是编写赋值语句:

new_list=['title','plays']

但是你可能想要提出一个更一般的问题,例如"如何从列表中的前两个元组中提取第二个项目?"像这样:

new_list = [alist[0][1], alist[1][1]]

或者你的意思是,"如何从列表中的每个元组中提取第二项?"像这样:

new_list = [t[1] for t in alist]

答案 1 :(得分:2)

alist = [(0, 'title', 'TEXT', 0, None, 0),(0, 'plays', 'integer', 0, None, 0)]
new_list = [alist[0][1], alist[1][1]]

检查,

print(new_list)

<强>解释

这一行:

alist = [(0, 'title', 'TEXT', 0, None, 0), (0, 'plays', 'integer', 0, None, 0)]

上面实际上是tuple list。因此,在alist内,有两个tuples。在每个tuple内,有6 objects

所以alist[0]表示您正在调用tuple内的第一个alist。 并且alist[0][1]表示您正在调用第一个second的{​​{1}}元素。像这样,您也可以考虑tuple