![](/img/trans.png)
[英]identify if a row of table_1 belongs to a row of table_2 - Python
[英]Identify if there is a repetition per row in Python
我对Python很陌生。
我正在尝试确定某项是否在列中重复。
如果我有:
x = [a, b, c, d, d, d, e, f, f]
我想得到:
rep = [no, no, no, no, yes, yes, no, no, yes]
我可以使用for
循环吗? 还是应用功能? 任何指导将不胜感激。
从可复制对象开始,例如
>>> x = ['a', 'b', 'c', 'd', 'd', 'd', 'e', 'f', 'f']
您可以使用列表理解并执行
>>> [x[:i+1].count(el)>1 for i,el in enumerate(x)]
[False, False, False, False, True, True, False, False, True]
如果要将布尔值转换为是/否,只需执行
>>> ['yes' if x[:i+1].count(el)>1 else 'no' for i,el in enumerate(x)]
['no', 'no', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']
使用集合跟踪您所看到的内容,并根据元素是否在集合中附加条件:
x = ['a', 'b', 'c', 'd', 'd', 'd', 'e', 'f', 'f']
is_dupes = []
seen = set()
for e in x:
if e in seen:
is_dupes.append('yes')
else:
is_dupes.append('no')
seen.add(e)
is_dupes
# ['no', 'no', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']
当然,您要做的就是遍历列表中的连续对项,并检查每对中的两个项是否相等。 有一个方便的函数可以用来执行此操作,称为pairwise()
,它的实现在itertools软件包文档中给出 ,或者您可以直接从more-itertools库中直接使用它。 您可以这样使用它:
for item1, item2 in pairwise(rep):
# choose yes or no
我实际上建议将其放在列表理解中,这样您就可以从一开始就将结果建立到列表中。
[ (choose yes or no) for item1, item2 in pairwise(rep)]
然后,您将不得不在前面加上一个额外的'no'
,因为第一个元素等于之前没有任何内容。
请问这个家庭作业问题的网址是什么?
#! /usr/bin/env python3
def y_or_n(bool):
return 'yes' if bool else 'no'
def rep(xs):
seen = set()
ret = []
for x in xs:
ret.append(y_or_n(x in seen))
seen.add(x)
return ret
if __name__ == '__main__':
print(rep('a b c d d d e f f'.split()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.