简体   繁体   English

使用正则表达式比较元组? 蟒蛇

[英]Comparing tuples using regex? Python

I have a dictionary where the keys are tuples of n elements. 我有一本字典,其中的键是n个元素的元组。 Say I want to find only tuples whose n-1 elements match, and the other one can be of any value. 假设我只想查找n-1个元素匹配的元组,另一个元组可以是任何值。 For example, I want the first 6th elements to be set to 100, and the 7th can be anything and I have these tuples as keys: 例如,我希望将第6个元素设置为100,第7个可以是任意值,并且我将这些元组作为键:

 1. (100,100,100,100,100,45,54)
 2. (100,100,100,100,100,100,54)
 3. (100,100,100,100,100,100,54)
 4. (100,100,100,100,100,100,54)
 5. (100,100,100,100,100,23,54)

Then I only need key 2-4, as the first and the fifth hold a value different than 100 in the 6th element. 然后,我只需要键2-4,因为第一个和第五个键在第6个元素中的值不同于100。 Of course I can compare each element individually when going over all keys, but I am thinking maybe there's a better way. 当然,遍历所有键时,我可以分别比较每个元素,但是我认为也许有更好的方法。 Any ideas of how I can do it in Python? 关于如何在Python中执行此操作的任何想法?

Thanks 谢谢

您可以进行列表理解:

matched = [x for x in tuples if x[:6] == (100,100,100,100,100,100)]

这样的事情应该起作用:

matched = [x for x in dict.keys if len(set(x[:6])) == 1]

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

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