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. 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
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:
['m', 'a', 'n']
[['m', 'a', 'n']]
[['m', 'a', 'n'], ['o', 'h'], ['m', 'a', 'n']]
You would need to
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.