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

2024-09-27 00:14:41 发布

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

下面的代码段接受两个参数,比较其中包含的值并打印任何匹配项

from sys import argv

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

一个人如何适应这种情况来处理一个未知的和潜在的无限量(或非常大)的论点?我尝试对参数进行迭代并将它们传递给函数,但是在没有已知数量的参数的情况下,如何对所有参数调用set()并引用它们? 期望:

#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'} 


Tags: frompyimportoutput参数代码段sys情况
2条回答

您可以迭代sys.argv并使用&=运算符。如果用参数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)

然后打印:

{'n'}

使用^{}^{}方法,实际上不需要将参数转换为集合(当然,除了一个)

the non-operator version[s] of ... intersection() ... method[s] will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets.

所以你可以这样做:

import sys

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

相关问题 更多 >

    热门问题