Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将字典中的相同值分配给另一个字符串列表_Python_String_List_For Loop - Fatal编程技术网

Python 如何将字典中的相同值分配给另一个字符串列表

Python 如何将字典中的相同值分配给另一个字符串列表,python,string,list,for-loop,Python,String,List,For Loop,我试图将字符串转换为数字,然后为另一个字符串列表中的相同单词指定相同的值。假设我有下面这样的字符串。我使用字典转换为值,如下代码所示。现在我需要给列表B中的同一个字符串分配相同的值,并且输出应该类似于resu B A='hello world how are you doing'` res_A = [1, 2, 3, 4, 5, 6] B=['hello world how', 'hello are' ,'hello', 'hello are you doing'] res_B = [[1,

我试图将字符串转换为数字,然后为另一个字符串列表中的相同单词指定相同的值。假设我有下面这样的字符串。我使用字典转换为值,如下代码所示。现在我需要给列表B中的同一个字符串分配相同的值,并且输出应该类似于resu B

A='hello world how are you doing'` 
res_A = [1, 2, 3, 4, 5, 6]

B=['hello world how', 'hello are' ,'hello', 'hello are you doing']
res_B = [[1,2,3],[1,4],[1],[1,4,5,6]]

再次使用列表理解,并使用以前的相同词典:

res_B = [
    [d[word] for word in phrase.lower().split()]
    for phrase in B
]

这里有一个循序渐进的实用方法

#创建查找字典
lookup={word:word的索引,zip中的索引(A.split(“”),res_A)}
#将每个要替换的句子映射为每个单词的查找值
res_B=[list(map)(lambda x:lookup[x],句子.split(“”),
(B)中的句子)

我将映射更改为dict理解。这样可读性更好。当然这里没有错误检查,所以不要在生产代码中使用。至少应检查
映射中是否存在
word
res_B = [
    [d[word] for word in phrase.lower().split()]
    for phrase in B
]
# map words from A into indices 1..N
mapping = {k: v for v, k in enumerate(A.split(), 1)}
# find mappings of words in B
B_res = [[mapping[word] for word in s.split()] for s in B]