我试图将如下所示的每个列表值分成两个以空格作为分隔符的变量。但我无法在列表中这样做。有没有更好的方法呢?请告诉我。
List1 = ['help show this help message and exit','file Output to the text file']
for i in range(strlist.__len__()):
# In this loop I want to break each list into two variables i.e. help, show this help message and exit in two separate string variables.
print(strlist[i])
最佳答案
用 split(None, 1)
分隔第一个空格:
>>> for item in List1:
... print(item.split(None, 1))
...
['help', 'show this help message and exit']
['file', 'Output to the text file']
然后,如果需要,您可以将结果解包到单独的变量中:
>>> for item in List1:
... key, value = item.split(None, 1)
... print(key)
... print(value)
...
help
show this help message and exit
file
Output to the text file
关于python - 用空格分隔符打破列表值 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36432373/