我试图将每个列表值分解为如下所示的两个变量,其中空格作为分隔符.但是我无法在列表中这样做.有没有更好的方法呢?请告诉我.
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])
Run Code Online (Sandbox Code Playgroud)
由第一个空格拆分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']
Run Code Online (Sandbox Code Playgroud)
如果需要,您可以将结果解压缩到单独的变量中:
>>> 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
Run Code Online (Sandbox Code Playgroud)