简体   繁体   English

嵌套列表理解示例

[英]Nested List Comprehensions Example

Problem 问题

I have next list: 我有下一个清单:

a = (('_a_1', '_a_2'), [0.3, 0.6]) 
b = (('_a_3', '_a_4'), [0.15, 0.56]) 
c = (('_a_5', '_a_6'), [0.22, 0.6])

l = [a, b, c]

What I wan't: choose first tuples of list and remove _a_ labels. 我不想:选择列表的第一个元组并删除_a_标签。 Result: 结果:

[['1','2'],['3','4'],['5','6']]

What I tried 我尝试了什么

I know I can do it using list comprehension . 我知道我可以使用列表理解来做到这一点。 But I can't comprehend it :D What I'm trying: 但我无法理解:D我正在尝试:

[ el.replace('_a_','') for m in l for el in m[0]]

result: 结果:

['1', '2', '3', '4', '5', '6']

I think it is closed to right solution. 我认为它对于正确的解决方案是封闭的。 Just add something like: 只需添加以下内容:

[ [el.replace('_a_','') for m in l] for el in m[0]]

But it doesn't work... 但它不起作用......

Here is one way using str.split : 这是使用str.split一种方法:

a = (('_a_1', '_a_2'), [0.3, 0.6]) 
b = (('_a_3', '_a_4'), [0.15, 0.56]) 
c = (('_a_5', '_a_6'), [0.22, 0.6])

res = [[i.split('_')[-1], j.split('_')[-1]] for (i, j), k in [a, b, c]]

# [['1', '2'], ['3', '4'], ['5', '6']]

You can also use str.replace : 你也可以使用str.replace

res = [[i.replace('_a_', ''), j.replace('_a_', '')] for (i, j), k in [a, b, c]]

As suggested by @Ev.Kounis, you can also write this functionally: 正如@ Ev.Kounis所建议的那样,你也可以在功能上写这个:

res = [list(map(lambda x: x.rsplit('_', 1)[-1], k)) for k, _ in [a, b, c]]

Nested list comprehensions require specific ordering , intuitive to some but not to others. 嵌套列表推导需要特定的排序 ,对某些人而言是直观的,而对其他人则不直观。 The above solutions avoid them altogether. 上述解决方案完全避免了它们。

You were close: 你很亲密:

a = (('_a_1', '_a_2'), [0.3, 0.6]) 
b = (('_a_3', '_a_4'), [0.15, 0.56]) 
c = (('_a_5', '_a_6'), [0.22, 0.6])

l = [a, b, c]

[ [el.replace('_a_','') for el in tup[0]] for tup in l]
# [['1', '2'], ['3', '4'], ['5', '6']]
res=[[j.replace("_a_","") for j in i[0]]  for i in l]
#OUT
[['1', '2'], ['3', '4'], ['5', '6']]

Another way of doing it would be to use the zip function: 另一种方法是使用zip功能:

a = (('_a_1', '_a_2'), [0.3, 0.6]) 
b = (('_a_3', '_a_4'), [0.15, 0.56]) 
c = (('_a_5', '_a_6'), [0.22, 0.6])

l = [[elem[0][-1],elem[1][-1]] for elem in list(zip(a,b,c))[0]]

print(l)

Output: 输出:

[['1', '2'], ['3', '4'], ['5', '6']]

You can go with regex without splitting it : 你可以使用正则表达式而不拆分它:

import re
pattern=r'[0-9]+'

print([tuple(map(lambda x:re.search(pattern,x).group(),i[0])) for i in l])

output: 输出:

[('1', '2'), ('3', '4'), ('5', '6')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM