当每个项目也包含在另一个元组中时如何从元组列表中获取第一个项目
How to get the first items from a list of tuples when each item is also wrapped in another tuple
所以我有这个列表,它是使用 SQLite 的 SELECT 请求的结果:
test = [(('over1.5',), 109),
(('ht1over0.5',), 101),
(('hgover0.5',), 78),
(('over2.5',), 68),
(('agover0.5',), 60)]
如何从每个元组中提取第一项,以便预期输出为:
['over1.5', 'ht1over0.5', 'hgover0.5', 'over2.5', 'agover0.5']
我想它必须用 re.findall
完成,但我不知道如何编写搜索模式。
试试这个正则表达式模式:
\(\('(.*?)',\),\s(\d+)
它首先匹配“(('
”,然后创建一个 Group 1
,其中包含任意数量的任意字符(这将包含密钥),然后匹配“',),
”和最后创建一个 Group 2
任意位数。
这将为您提供 key in Group 1
和 value in Group 2
。
假设这是 Python,您可以使用列表理解。您将需要提取每个 tuple
:
中第一个元素的第一个(唯一)值
res = [i[0][0] for i in test]
# ['over1.5', 'ht1over0.5', 'hgover0.5', 'over2.5', 'agover0.5']
所以我有这个列表,它是使用 SQLite 的 SELECT 请求的结果:
test = [(('over1.5',), 109),
(('ht1over0.5',), 101),
(('hgover0.5',), 78),
(('over2.5',), 68),
(('agover0.5',), 60)]
如何从每个元组中提取第一项,以便预期输出为:
['over1.5', 'ht1over0.5', 'hgover0.5', 'over2.5', 'agover0.5']
我想它必须用 re.findall
完成,但我不知道如何编写搜索模式。
试试这个正则表达式模式:
\(\('(.*?)',\),\s(\d+)
它首先匹配“(('
”,然后创建一个 Group 1
,其中包含任意数量的任意字符(这将包含密钥),然后匹配“',),
”和最后创建一个 Group 2
任意位数。
这将为您提供 key in Group 1
和 value in Group 2
。
假设这是 Python,您可以使用列表理解。您将需要提取每个 tuple
:
res = [i[0][0] for i in test]
# ['over1.5', 'ht1over0.5', 'hgover0.5', 'over2.5', 'agover0.5']