简体   繁体   English

在 Python 中迭代和比较未知数量的输入

[英]Iterate and compare unknown amount of input in Python

The following snippet takes two arguments, compares the values contained therein and prints any matches.以下代码段采用两个参数,比较其中包含的值并打印任何匹配项。

from sys import argv

print(set(argv[1]) & set(argv[2]))
#Output: python multicompare.py man fan
#{'n', 'a'}

How would one adapt this to deal with an unknown and potentially unlimited (or very large) amount of arguments?人们将如何调整它以处理未知且可能无限(或非常大)数量的参数? I tried iterating over the arguments and passing them to a function, but without having a known amount of arguments, how can I call set() against them all and reference them?我尝试迭代参数并将它们传递给一个函数,但没有已知数量的参数,我如何对它们全部调用 set() 并引用它们? What's expected:预期:

#Output: python3 multicompare.py man fan dan tan han
# {'n', 'a'}
#Output: python3 multicompare.py man fan dan can fin tin mountain happen trappen
# {'n'} 

You can iterate over sys.argv and use &= operator.您可以遍历sys.argv并使用&=运算符。 If you call this with arguments man fan dan can fin tin mountain happen trappen :如果你用参数来调用这个man fan dan can fin tin mountain happen trappen

import sys

s = set(sys.argv[1])

for a in sys.argv[2:]:
    s &= set(a)

print(s)

Then it prints:然后它打印:

{'n'}

Using the intersection method of set s, you don't actually need to convert the arguments to sets (well, that is except one).使用set s 的intersection方法,您实际上不需要将参数转换为集合(好吧,除了一个)。

the non-operator version[s] of ... intersection() ... method[s] will accept any iterable as an argument. ... intersection() ...method[s] 的非运算符版本 [s] 将接受任何可迭代对象作为参数。 In contrast, their operator based counterparts require their arguments to be sets.相比之下,它们的基于运算符的对应物需要设置它们的参数。

So you could do something like:所以你可以这样做:

import sys

print(set(sys.argv[1]).intersection(*sys.argv[2:]))

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

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