现在我有这个嵌套列表和字典:
phrases = [['Lionhearted', 'Baby Preach'], ['Lionhearted Baby', 'Preach'], ['Lionhearted', 'Baby', 'Preach']]
artist_info = {u'Baby': u'Baby by Justin Bieber', u'Lionhearted': u'Lionhearted by Porter Robinson', u'Preach': u'Preach by Drake', u'Baby Preach': u:'Baby Preach by some pop singer'}
基本上,我想要做的是尝试使用来自artist_info的值替换短语中的值(如果存在匹配),另外我想省略该特定的嵌套列表。因为有'Lionhearted'
,'Baby'
,'婴儿讲道'和'Preach'
,输出将读取如下内容:
phrases2 = [['Lionhearted by Porter Robinson','Baby Preach by some pop singer'] ['Lionhearted by Porter Robinson', 'Baby by Justin Bieber', 'Preach by Drake']]
有办法做到这一点吗?我已经在这几个小时了。重要的是,这三个短语导致了“狮子会婴儿讲道”#34;的顺序。我有点像Python菜鸟,但我还没能找到一个类似的例子。
答案 0 :(得分:1)
这是你在找什么?在您的示例中,如果该子列表中的任何项目不在字典phrases
中,则您似乎想要省略artist_info
中的子列表。在执行您提到的替换之前,下面的代码会这样做。
phrases = [['Lionhearted', 'Baby Preach'], ['Lionhearted Baby', 'Preach'], ['Lionhearted', 'Baby', 'Preach']]
artist_info = {u'Baby': u'Baby by Justin Bieber', u'Lionhearted': u'Lionhearted by Porter Robinson', u'Preach': u'Preach by Drake', u'Baby Preach': u'Baby Preach by some pop singer'}
lst = filter(lambda x: all(y in artist_info for y in x), phrases)
phrases2 = map(lambda x: [artist_info[y] for y in x], lst)
print phrases2
答案 1 :(得分:0)
首先,我假设结果列表的排序顺序是任意的。
一步一步:
phrases = [['Lionhearted', 'Baby Preach'], ['Lionhearted Baby', 'Preach'], ['Lionhearted', 'Baby', 'Preach']]
artist_info = {u'Baby': u'Baby by Justin Bieber', u'Lionhearted': u'Lionhearted by Porter Robinson', u'Preach': u'Preach by Drake'}
phrases = [' '.join(item).split() for item in phrases]
phrases2 = set()
for item in phrases:
for word in item:
for key in artist_info:
if word in artist_info.get(key):
phrases2.add(artist_info.get(key))
phrases2 = list(phrases2)
print(*phrases2, sep='\n')
或者,理解:
phrases = [['Lionhearted', 'Baby Preach'], ['Lionhearted Baby', 'Preach'], ['Lionhearted', 'Baby', 'Preach']]
artist_info = {u'Baby': u'Baby by Justin Bieber', u'Lionhearted': u'Lionhearted by Porter Robinson', u'Preach': u'Preach by Drake'}
phrases2 = list({artist_info.get(key) for item in [' '.join(phrase).split() for phrase in phrases] for word in item for key in artist_info if word in artist_info.get(key)})
具有任一版本的phrases2
的内容:
['Baby by Justin Bieber', 'Lionhearted by Porter Robinson', 'Preach by Drake']
使用以下内容打印出来:
print(*phrases2, sep='\n')