a = 1
b = 2
我想将a:b插入空白的python列表
list = []
作为
a:b
这个的正确语法是什么,导致
[(a:b), (c:d)]
这样我就可以按照从最小到最晚的值对列表进行排序
答案 0 :(得分:8)
我们假设您的数据如下所示:
a: 15
c: 10
b: 2
有几种方法可以对数据进行排序。这个键/值数据最好存储为字典,如下所示:
data = {
'a': 15,
'c': 10,
'b': 2,
}
# Sort by key:
print [v for (k, v) in sorted(data.iteritems())]
# Output: [15, 2, 10]
# Keys, sorted by value:
from operator import itemgetter
print [k for (k, v) in sorted(data.iteritems(), key = itemgetter(1))]
# Output: ['b', 'c', 'a']
如果将数据存储为元组列表:
data = [
('a', 15),
('c', 10),
('b', 2),
]
data.sort() # Sorts the list in-place
print data
# Output: [('a', 15), ('b', 2), ('c', 10)]
print [x[1] for x in data]
# Output [15, 2, 10]
# Sort by value:
from operator import itemgetter
data = sorted(data, key = itemgetter(1))
print data
# Output [('b', 2), ('c', 10), ('a', 15)]
print [x[1] for x in data]
# Output [2, 10, 15]
答案 1 :(得分:7)
如何将键值对插入python列表?
你不能。你可以做的是"模仿"这通过将2个元素的元组附加到列表中:
a = 1
b = 2
some_list = []
some_list.append((a, b))
some_list.append((3, 4))
print some_list
>>> [(1, 2), (3, 4)]
但正确/最好的方法是使用字典:
some_dict = {}
some_dict[a] = b
some_dict[3] = 4
print some_dict
>>> {1: 2, 3: 4}
注意:
list
,因为它会隐藏其内置实现。将其命名为其他内容,例如some_list
,L
,... 答案 2 :(得分:0)
概述:在此代码示例中,我演示了如何对句子列表进行标记化,然后存储包含键和值对的字典,其中,值是对每个句子的出现次数进行计数的标记化词。
index=np.arange(0,len(sentences))
wordfreq = {}
bagList=[]
for i in index:
sentence=sentences[i]
keyId=keys[i]
if(len(sentence)>0):
tokens=sum([word_tokenize(sentence)],[])
words_frequency = FreqDist(tokens)
wordfreq={}
for token in tokens:
if token not in wordfreq.keys():
wordfreq[token] = 1
else:
wordfreq[token] += 1
bagList.append({'keyId':keyId, 'words': wordfreq})
枚举词典项列表使用
for dictionaryValues in bagList:
print(dictionaryValues['keyId'])
print(dictionaryValues['words'])
获取键值对使用项
uncommon=dict()
for dictionaryItem in bagList:
words=dictionaryItem['words']
for key,(word,count) in enumerate(words.items()):
if word in uncommon:
uncommon[word]+=1
else:
uncommon[word]=1
uncommon = {key: value for key, value in uncommon.items() if (value<=3 )}