如何在嵌套列表中就地拆分单词
How to split words in-place, within a nested list
这是我的代码:
abc
是一个多维列表
输入列表:abc = [['word1_word1.5','word2'],['word1_word1.5','word2']]
for i in range(len(abc)):
for j in range(len(abc[i])):
if "word1_word1.5" in abc[i][j]:
newword = abc[i][j].split("_")
// Replace the abc[i][j] with "word1" and "word1.5"
预期输出:
abc = [['word1','word1.5','word2'],['word1','word1.5','word2']]
for item in abc:
for ele in item:
if ele in xyz:
split_word = ele.split("_")
此逻辑 return 您以存储在 split_word
中的列表形式拆分单词。
现在将 abc
中的原始单词替换为 split_word
.
希望对您有所帮助:)
for lst in abc:
for n in range(len(lst)):
if lst[n] in xyz:
wrd = lst.pop(n)
lst += wrd.split("_")
这会将存在于 xyz
中的单词替换为其拆分版本,在 abc
中就地
鉴于此:
>>> abc = [['word1_word1.5', 'word2', 'word3', 'word4_word4.5'], ['word5_word5.5', 'word2', 'word3', 'word1_word1.5']]
拆分每个单词:
>>> [[w.split('_') for w in l] for l in abc]
[[['word1', 'word1.5'], ['word2'], ['word3'], ['word4', 'word4.5']], [['word5', 'word5.5'], ['word2'], ['word3'], ['word1', 'word1.5']]]
连接子列表:
>>> from itertools import chain
>>> [list(chain.from_iterable(w.split('_') for w in l)) for l in abc]
[['word1', 'word1.5', 'word2', 'word3', 'word4', 'word4.5'], ['word5', 'word5.5', 'word2', 'word3', 'word1', 'word1.5']]
仅当 w
出现在 xyz
时拆分:
>>> xyz = {'word1_word1.5', 'word5_word5.5', 'word4_word4.5'}
>>> [list(chain.from_iterable(w.split('_') if w in xyz else [w] for w in l)) for l in abc]
[['word1', 'word1.5', 'word2', 'word3', 'word4', 'word4.5'], ['word5', 'word5.5', 'word2', 'word3', 'word1', 'word1.5']]
这是我的代码:
abc
是一个多维列表
输入列表:abc = [['word1_word1.5','word2'],['word1_word1.5','word2']]
for i in range(len(abc)):
for j in range(len(abc[i])):
if "word1_word1.5" in abc[i][j]:
newword = abc[i][j].split("_")
// Replace the abc[i][j] with "word1" and "word1.5"
预期输出:
abc = [['word1','word1.5','word2'],['word1','word1.5','word2']]
for item in abc:
for ele in item:
if ele in xyz:
split_word = ele.split("_")
此逻辑 return 您以存储在 split_word
中的列表形式拆分单词。
现在将 abc
中的原始单词替换为 split_word
.
希望对您有所帮助:)
for lst in abc:
for n in range(len(lst)):
if lst[n] in xyz:
wrd = lst.pop(n)
lst += wrd.split("_")
这会将存在于 xyz
中的单词替换为其拆分版本,在 abc
鉴于此:
>>> abc = [['word1_word1.5', 'word2', 'word3', 'word4_word4.5'], ['word5_word5.5', 'word2', 'word3', 'word1_word1.5']]
拆分每个单词:
>>> [[w.split('_') for w in l] for l in abc]
[[['word1', 'word1.5'], ['word2'], ['word3'], ['word4', 'word4.5']], [['word5', 'word5.5'], ['word2'], ['word3'], ['word1', 'word1.5']]]
连接子列表:
>>> from itertools import chain
>>> [list(chain.from_iterable(w.split('_') for w in l)) for l in abc]
[['word1', 'word1.5', 'word2', 'word3', 'word4', 'word4.5'], ['word5', 'word5.5', 'word2', 'word3', 'word1', 'word1.5']]
仅当 w
出现在 xyz
时拆分:
>>> xyz = {'word1_word1.5', 'word5_word5.5', 'word4_word4.5'}
>>> [list(chain.from_iterable(w.split('_') if w in xyz else [w] for w in l)) for l in abc]
[['word1', 'word1.5', 'word2', 'word3', 'word4', 'word4.5'], ['word5', 'word5.5', 'word2', 'word3', 'word1', 'word1.5']]