如何遍历字符串列表并将每个字符串转换为独立列表?
批量将列表中字符串转为拆分后的子列表
你可以用列表推导式快速完成批量拆分,这是Python里最简洁的遍历处理方式:
list_of_strings = ["the 1st string", "the 2nd string", "the 3rd string"] # 遍历每个字符串并拆分,生成包含子列表的新列表 split_lists = [s.split(" ") for s in list_of_strings]
执行后split_lists的结果是:[['the', '1st', 'string'], ['the', '2nd', 'string'], ['the', '3rd', 'string']]
如果你更习惯用常规的for循环,也可以这样写:
list_of_strings = ["the 1st string", "the 2nd string", "the 3rd string"] split_lists = [] for string_item in list_of_strings: # 拆分每个字符串后添加到新列表 split_lists.append(string_item.split(" "))
要是需要把拆分后的每个子列表单独赋值给变量(比如你之前的first_list),可以用解包操作:
first_list, second_list, third_list = split_lists
注意这种方式要求原列表的长度和变量数量完全匹配。
内容的提问来源于stack exchange,提问作者Jace Barnett
相关产品推荐
相关产品推荐

