简体   繁体   English

Python 嵌套列表:如何拆分列表的内部字符串元素?

[英]Python nested list: How to split the inner string elements of a list?

Assuming I have a list, which contains string elements.假设我有一个包含字符串元素的列表。 How can I split the string element of every cell of every index of the list, without having them all mixed up with each other?如何拆分列表中每个索引的每个单元格的字符串元素,而不会将它们全部混合在一起? I still want every element separated from the one in the other indexes.我仍然希望每个元素都与其他索引中的元素分开。 Is this possible?这可能吗? For example, if I have this input from the user:例如,如果我从用户那里得到这个输入:

user_input = ['hello', 'hey', 'hi']

How can I make it look like this:我怎样才能让它看起来像这样:

split_list = [['h', 'e', 'l', 'l', 'o'], ['h', 'e', 'y'], ['h', 'i']]

You can use the list function on a string to split the string into a list containing each of its characters.您可以对字符串使用 list 函数将字符串拆分为包含其每个字符的列表。

>>> strings = ['some', 'strings', 'here']
>>> list(map(lambda x: list(x), strings))
[['s', 'o', 'm', 'e'], ['s', 't', 'r', 'i', 'n', 'g', 's'], ['h', 'e', 'r', 'e']]

If you want to split by a string like you would with the .split() function, you could loop through the elements in the array.如果您想像使用 .split() 函数那样按字符串拆分,则可以循环遍历数组中的元素。

test_list = ["String 1", "String 2"]

def split_list(input_list, delimiter):
    for i in range(len(input_list)):
        input_list[i] = input_list[i].split(delimiter)

    return input_list

print(split_list(test_list, " "))

Returns: [['String', '1'], ['String', '2']]

In python, so split on every character, the way is using the list constructor, so every element of the given input is treated as a value of the list.在python中,因此对每个字符进行拆分,方式是使用list构造函数,因此给定输入的每个元素都被视为列表的值。 Combinate that with a list comprehension and you're done将它与列表理解相结合,你就完成了

user_input = ['hello', 'hey', 'hi']
split_list = [list(x) for x in user_input]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM