[英]What's the best way to split a string into fixed length chunks and work with them in Python?
[英]What is the best way to split a variable length string into variables in Python?
假設我有一個由可變長度的逗號分隔的整數字符串。 拆分字符串並將整數存儲為變量的最佳方法是什么?
目前,我有以下內容。
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至少設置為“無”,並且如果項數大於三,則僅使用前三個值。
演示:
>>> 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)
只是Martjin的附錄。 將其轉換為一個函數,以顯示您為什么可以使用它。 您可以使用以下方法進行動態前哨
def store(mylist,expsiz = 10, dflt = None):
return mylist + [dflt]*(expsiz-len(mylist))
>>> mylist = [1,2,5]
>>> fixedlen = store(mylist)
>>> print fixedlen
[1,2,5,None,None,None,None,None,None,None]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.