简体   繁体   English

如何将字符串分割成嵌套列表中的单个字符

[英]how to slice a string into single characters in a nested list

Could you please share some knowledge?请问可以分享一些知识吗? How can I slice a string for a single characters in the nested list?如何为嵌套列表中的单个字符分割字符串? See some examples below...请参阅下面的一些示例...

str1 = 'man'
str2 = ['man']
str3 = ['man oh man']

x1=[str1[i:i+1] for i in range(0, len(str1), n)]
x2=[str2[i:i+1] for i in range(0, len(str2), n)]
x3=[str3[i:i+1] for i in range(0, len(str3), n)]

print(x1)
print(x2)
print(x3)
#actual output

>>>
['m', 'a', 'n']
[['man']]
[['man oh man']]
>>>

#expected output

>>>
['m', 'a', 'n']
[['m', 'a', 'n']]
[['m', 'a', 'n'],['o', 'h'],['m', 'a', 'n']]
>>>

You can simply build a list from the strings with the list constructor in order to split them into single characters.您可以使用list构造函数简单地从字符串构建一个列表,以便将它们拆分为单个字符。 For the examples above:对于上面的例子:

str2 = ['man']
str3 = ['man oh man']

[list(i) for i in str2]
# [['m', 'a', 'n']]

[list(i) for s in str3 for i in s.split()]
# [['m', 'a', 'n'], ['o', 'h'], ['m', 'a', 'n']]

for list you can do this对于列表,您可以这样做

[[j for j in i] for i in str2[0].split()]
[[j for j in i] for i in str3[0].split()]

for string you can do this对于字符串,你可以这样做

[i for i in str1]

Here is another option altering your code the least.这是另一种最少更改代码的选项。 Had to define n=1 to be able to apply your code:必须定义n=1才能应用您的代码:

n = 1
str1 = 'man'
str2 = ['man']
str3 = ['man oh man']
str3 = str3[0].split()
x2 = []

x1=[str1[i:i+1] for i in range(0, len(str1), n)]
x2.append([str2[0][i:i+1] for i in range(0, len(str2[0]), n)])
x3=[ list(k[0]) for k in [str3[i:i+1] for i in range(0, len(str3), n)]]

print(x1)
print(x2)
print(x3)

Output: Output:

['m', 'a', 'n']
[['m', 'a', 'n']]
[['m', 'a', 'n'], ['o', 'h'], ['m', 'a', 'n']]

You would need to你需要

  1. Check if the input already is a list or not检查输入是否已经是列表
  2. If it's a list split each string in the list by spaces before further splitting into characters如果它是一个列表,则在进一步拆分为字符之前将列表中的每个字符串用空格拆分

Try this:尝试这个:

def split_list_string(l):

  if not isinstance(l, list):
    return list(l)
  else:
    return [[y for y in x.split()] for x in l]


print(split_list_string(str1))
print(split_list_string(str2))
print(split_list_string(str3))

This yields your expected output.这会产生您预期的 output。

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

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