在Python中根据字符串屏蔽列表

2024-09-28 22:19:23 发布

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

我有以下内容:

  str1 ='-CGCG-G'
  ls1 = [0,1,2,3,4,5,6]
  # length of ls and str always the same
  # and the value of ls1 can be anything. It is not the index of str1

我要做的是根据str1屏蔽列表l1, 通过在字符串中保留对应位置不是-的列表成员。 屈服

^{pr2}$

如何在Python中方便地实现这一点呢? 我看了看itertools.compress,但我想不出办法 把它用于我的目的。在


Tags: andofthe列表valuebealwayscan
3条回答

您也可以使用^{}来执行此操作。在

>>> from itertools import compress
>>> ls1 = [0, 1, 2, 3, 4, 5, 6]
>>> str1 = '-CGCG-G'
>>> f = compress(ls1, [0 if j == '-' else 1 for j in list(str1)])    # compress([0, 1, 2, 3, 4, 5, 6], [0, 1, 1, 1, 1, 0, 1])
>>> filtered = [i for i in f]
>>> filtered
[1, 2, 3, 4, 6]

另一种方法是使用^{}

>>> str1 ='-CGCG-G'
>>> ls1 = [0,1,2,3,4,5,6]
>>> [a for idx, a in enumerate(a) if str1[idx] != '-']
[1, 2, 3, 4, 6]

您可以使用zip组合这两者,然后在字符串中的字符是-时使用列表理解进行筛选:

output = [num for char, num in zip(str1, ls1) if char != '-']

zip函数将获取两个列表,并将它们“组合”在一起。在这种情况下,执行zip(str1, ls1)将产生:

^{pr2}$

从那里,迭代列表并过滤掉字符是破折号的所有对就相对简单了。在

相关问题 更多 >