[英]What's the best way to parse values from a variable length string?
Suppose I have a string of integers separated by commas of variable length. 假设我有一个由可变长度的逗号分隔的整数字符串。 What is the best way to split the string and update variables with values if they exist? 拆分字符串并使用值更新变量的最佳方法是什么?
Currently, I have the following. 目前,我有以下几点。
a, b, c = 10, 10, 1 #default values
mylist = [int(x) for x in input.split(',')]
if len(mylist) == 2: a, b = mylist
else: a, b, c = mylist
Is there a more efficient way of doing this? 有更有效的方法吗?
a, b, c = 10, 10, 1 #default values
mylist = [int(x) for x in input.split(',')]
a, b, c = mylist + [a, b, c][len(mylist):]
I think the reason this is ugly is that it's non-Pythonic to treat local variables in aggregate; 我认为这个丑陋的原因是它总是处理局部变量是非Pythonic的; instance members would be more appropriate. 实例成员会更合适。
You could use a helper function: 你可以使用辅助函数:
def f(a=10, b=10, c=1):
return a, b, c
a, b, c = f(*map(int, input.split()))
This won't be faster – it's just a different way to do it that just crossed my mind. 这不会更快 - 它只是一种不同的方式来做到这一点,只是我的想法。
defaults=[10,10,1]
mylist=[int(x) for x in ipt.split(',')]
defaults[:len(mylist)]=mylist
a,b,c=defaults
This changes defaults
though... You to avoid that, something like this would work: 这改变了defaults
...你要避免这种情况,这样的事情会起作用:
defaults=[10,10,1]
mylist=[int(x) for x in ipt.split(',')]
temp_defaults=defaults[:]
temp_defaults[:len(mylist)]=mylist
a,b,c=temp_defaults
Also, be careful using input
as a variable name. 另外,请注意使用input
作为变量名称。 It's the name of a python built-in so you're removing your easy access to that function. 它是内置python的名称,因此您可以轻松访问该功能。
Use slicing to combine the user input with the list of default arguments: 使用切片将用户输入与默认参数列表组合在一起:
>>> defaults = [10, 10, 1]
>>> user_input = '15 20'
>>> user_ints = map(int, user_input.split())
>>> combined = user_ints + defaults[len(user_ints):]
>>> a, b, c = combined
izip_longest
allows to take the length of the default values if longer: 如果更长, izip_longest
允许采用默认值的长度:
>>> from itertools import izip_longest
>>> inp = '3, 56'
>>> a, b, c = [i if i else j for i, j in izip_longest([int(x) for x in inp.split(',')], (10, 10, 1))]
>>> a, b, c
(3, 56, 1)
a, b, c = (map(int, user_input.split(',')) + [20,20,10])[:3]
or 要么
def parse(user_input, *args):
return (map(int, user_input.split(',')) + list(args))[:len(args)]
>>> a, b, c = parse('1,2', 20, 20, 10)
>>> a, b, c
(1, 2, 20)
>>> a, b, c, d = parse('1,2,3,4,5', 0, 0, 0, 0)
>>> a, b, c, d
(1, 2, 3, 4)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.