如何将字符串列表拆分后分别存入独立变量以获取目标输出?
将列表中每个字符串拆分为独立单词列表并存入变量
需求与问题背景
用户拥有如下Python列表:
my_list = ['a climber stops to take a drink while climbing a snow covered mountain ', 'a man holding a cup on a snow mountain ', 'a man in a yellow suit is holding up a cup while standing in snow ']
需要把列表里的每个字符串单独拆分成单词列表,分别存入reference1、reference2、reference3三个独立变量,目标输出如下:
reference1 = ['a', 'climber', 'stops', 'to', 'take', 'a', 'drink', 'while', 'climbing', 'a', 'snow', 'covered', 'mountain'] reference2 = ['a', 'man', 'holding', 'a', 'cup', 'on', 'a', 'snow', 'mountain'] reference3 = ['a', 'man', 'in', 'a', 'yellow', 'suit', 'is', 'holding', 'up', 'a', 'cup', 'while', 'standing', 'in', 'snow']
用户当前尝试的代码无法得到预期结果:
list = ['a climber stops to take a drink while climbing a snow covered mountain ', 'a man holding a cup on a snow mountain ', 'a man in a yellow suit is holding up a cup while standing in snow '] x = (','.join(list)) print(x) print('\n') y = x.split() print(y)
这段代码的问题是把所有字符串拼接成一个整体后再拆分,最终得到的是所有单词的大列表,没法拆分到独立变量里。
修正后的代码
直接对原列表的每个元素单独处理即可:
# 别用list当变量名,会覆盖Python内置的列表类型 my_list = ['a climber stops to take a drink while climbing a snow covered mountain ', 'a man holding a cup on a snow mountain ', 'a man in a yellow suit is holding up a cup while standing in snow '] # 逐个拆分每个字符串的单词,赋值给对应变量 reference1 = my_list[0].split() reference2 = my_list[1].split() reference3 = my_list[2].split() # 打印验证结果 print(reference1) print(reference2) print(reference3)
关键说明
split()方法默认会按任意空白字符拆分字符串,自动忽略字符串首尾的空格,完全符合需求。- 通过索引
my_list[0]、my_list[1]、my_list[2]直接访问原列表的每个元素,拆分后分别赋值给目标变量就行。 - 避免用
list作为变量名,这是Python的内置类型,用了会导致后续无法正常使用内置的列表功能。
内容的提问来源于stack exchange,提问作者Dixon Chaudhary
相关产品推荐
相关产品推荐

