假设我有一串由逗号分隔的可变长度的整数。拆分字符串并将整数存储到变量中的最佳方法是什么?
目前,我有以下内容。
input = sys.argv[1]
mylist = [int(x) for x in input.split(',')]
if len(mylist) == 2: a, b = mylist
else: a, b, c = mylist
有没有更有效的方法?
最佳答案
添加哨兵,然后将列表限制为 3 个元素:
a, b, c = (mylist + [None] * 3)[:3]
现在 a、b 和 c 至少设置为 None,如果项目数超过三个,则只使用前三个值。
演示:
>>> mylist = [1, 2]
>>> a, b, c = (mylist + [None] * 3)[:3]
>>> print a, b, c
1 2 None
>>> mylist = [1, 2, 3, 4]
>>> a, b, c = (mylist + [None] * 3)[:3]
>>> print a, b, c
1 2 3
如果您至少需要 2 个元素,请使用较少的 None 值并捕获 ValueError:
try:
a, b, c = (mylist + [None])[:3]
except ValueError:
print "You mast specify at least 2 values"
sys.exit(1)
关于python - 在 Python 中将可变长度字符串拆分为变量的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11313256/