同时枚举两个列表

问题描述 投票:1回答:5

我有两个列表:1.IPA符号列表-M2.单词列表-N

现在,我需要创建第三个列表X = [N,M],其中对于在单个单词中找到的每个IPA符号,我必须将1分配给新列表,并将0分配给新列表。例如,如果M = ['ɓ',' u”,“ l”,“ i”,“ r”,“ t”,“ə”,“ w”,“ a”,“ b”],为简单起见,N仅包含两个词= ['ɓuli',' rutə'],则输出应类似于X = [[1,1,1,1,0,0,0,0,0,0],[0,1,0,0,1,1,1,0,0,0]]

所以它是一种共现矩阵,但更简单-因为我不需要保存该符号在单词中出现的次数。当符号出现在适当位置的单词中时,我只需要给X赋1。也许我想得太多了,但似乎找不到找到两个列表索引的方法。这是我的代码段:

M = ['ɓ', 'u', 'l', 'i', 'r', 't', 'ə', 'w', 'a', 'b'] 
N = ['ɓuli', 'rutə']
X = np.zeros((len(N), len(M)))

for n_idx in range(len(N)):
    print('Current word index', n_idx)
    for symbol in N[n_idx]:
        if symbol in M:
            print(symbol, 'found, at word index', n_idx, ', and symbol index')
            # if found then ad to X at proper position

#Expected result
X = [[1,1,1,1,0,0,0,0,0,0], 
     [0,1,0,0,1,1,1,0,0,0]]
python string list nlp text-mining
5个回答
1
投票

您可以这样做。只需将您需要检查的单词与其他列表进行循环并进行比较即可。

M=['a','e','i','o','u']
N=['stack','overflow']
output=[]
for words in N:
    words_output=[]
    for w in words:
        o = 1 if w in M else 0
        words_output.append(o)
    output.append(words_output)

output:
[[0, 0, 1, 0, 0], [1, 0, 1, 0, 0, 0, 1, 0]]

0
投票

尝试这个

M = ['ɓ', 'u', 'l', 'i', 'r', 't', 'ə', 'w', 'a', 'b'] 
N = ['ɓuli', 'rutə']
result = []
for n in N:
    tmp = []
    for m in M:
        tmp.append(1 if m in list(n) else 0)
    result.append(tmp)
print(result)

0
投票

您可以使用此行建立这样的索引:

X = [[1 if e in s else 0 for e in M] for s in N]

这是一个在字母和单词上循环的双重理解列表。但是,您应该使用sklearn之类的库来更有效地执行此类操作(例如https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html


0
投票

请勿使用double for循环,因为这将导致O ^ 2时间复杂性。使用集合会越来越快:

M = ['a', 'b', 'q', 'o', 'd', 'e', 'b']
N = ['dog', 'ai', 'something']

# list to set
M_set = set(M)
N_set = set(N)

output = []

for word in N:
   output.append([])
   for letter in word:
       if set(letter).intersection(M):
           output[-1].append(1)
       else:
           output[-1].append(0)


print(output)
# will return [[1,1,0], [1, 0], [0,1,0,1,0,0,0,0,0]]

结果将与double for循环的情况完全相同!


0
投票

您可以尝试这个。

N=map(set,N)
[[int(i in word) for i in M] for word in N]
# [[1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 1, 1, 0, 0, 0]]
© www.soinside.com 2019 - 2024. All rights reserved.