python字典和列表:如何转换? [英] python dictionary and list: how to convert it?
问题描述
dic = {
'blahAA,
AA' :[
u'cat'
],
'blahBB,
BB':[
u'dog',
u'bird'
],
'blahCC,
CC':[
u'fish',
u'horse',
u'elephant'
]
}
blahXX是互联网链接,与XX的id。
如何将其转换为具有如下列表:
list = [['cat AA'],[ '狗鸟BB'],['鱼马大象CC']]
选项:
理想情况下,我想在Gtk界面(组合框)中显示每个元素(猫,狗鸟等),而不显示XX,想法是在选择时找到对应的互联网地址:
示例:
cat --Gtk - > blahAA
狗鸟--Gtk - > blahBB
鱼马大象--Gtk - > blahCC
可以吗?
谢谢
我的实际代码显示结果是:
choice = self.liste.get_active_text()#从用户
中的url在self.links中选择
如果URL在URL中:
adress = url
self。 champ.set_text(地址)#地址显示
>>> [v + [k.rsplit(',')[ - 1]] for k,v in dic.items()]
[['dog','bird','BB'],['cat ','AA'],['鱼','马','大象','CC']]
我不太明白您想要连接每个子列表中的所有值的目的,但可以使用连接
方法 str
:
>>> [''.join(v + [k.rsplit(',')[ - 1]])for k,v in dict.items()]
['dog bird BB','cat AA' '鱼马大象CC']
更新:
>>>对于k,v在dict.items())中的[''.join(v + [k]:5).rsplit(',')[ - 1]])
k [: - 5]
返回一个没有最后5个字符的新字符串(在我们的例子中 .html
)。
I have this type of dictionary:
dic = {
'blahAA,
AA': [
u'cat'
],
'blahBB,
BB': [
u'dog',
u'bird'
],
'blahCC,
CC': [
u'fish',
u'horse',
u'elephant'
]
}
blahXX is internet link, with XX the id. How to convert it to have a list like that:
list = [['cat AA'], ['dog bird BB'], ['fish horse elephant CC']]
Optionnal: Ideally, I would like to display each element (cat, dog bird, etc) in a Gtk interface (combobox), without displaying XX, with the idea to find the correspondant internet adress at the selection:
Example:
cat --Gtk--> blahAA
dog bird --Gtk--> blahBB
fish horse elephant --Gtk--> blahCC
Is it possible? Thanks
My actual code to display the results is:
choice = self.liste.get_active_text() # choice from the user
for url in self.links:
if id in url:
adress = url
self.champ.set_text(adress) # adress display
>>> [v + [k.rsplit(',')[-1]] for k, v in dic.items()]
[['dog', 'bird', 'BB'], ['cat', 'AA'], ['fish', 'horse', 'elephant', 'CC']]
I'm not really understand for what purpose you want to concatenate all values in each child list, but you can do it with join
method of str
:
>>> [' '.join(v + [k.rsplit(',')[-1]]) for k, v in dict.items()]
['dog bird BB', 'cat AA', 'fish horse elephant CC']
Update: if you want to remove .html
part from those urls, you'd do something like
>>> [' '.join(v + [k[:-5].rsplit(',')[-1]]) for k, v in dict.items()]
k[:-5]
returns a new string without last 5 characters (in our case .html
).
这篇关于python字典和列表:如何转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!