eval() 如何改变字典?这是一个例子:创建一个字典 -> print -> eval -> print
>>> a={'a':'a','b':'b'}
>>> print(a)
{'a': 'a', 'b': 'b'}
>>> eval('a == "a"',a)
True
>>> print(a)
{'a': 'a', '__builtins__': {'bytearray': <class 'bytearray'>, 'IndexError': <class 'IndexError'>, 'all': <built-in function all>, 'help': Type help() for interactive help, or help(object) for help about object., 'vars': <built-in function vars>, 'SyntaxError': <class 'SyntaxError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'memoryview': <class 'memoryview'>, 'isinstance': <built-in function isinstance>, '__build_class__': <built-in function __build_class__>, 'copyright': Copyright (c) 2001-2012 Python Software Foundation.
All Rights Reserved.
...
Run Code Online (Sandbox Code Playgroud) 我一直在考虑这个问题,但我没有得出任何结论(对于Python来说还不是很好).
我的字典看起来像这样:
{1: [dog, animal], 2: [square, shape], 3: [red, color]}
我打印出值,但字典按数字排序,这很好,但我想随机化它,所以我打印出这样的东西:
3
red
color
1
dog
animal
2
square
shape
Run Code Online (Sandbox Code Playgroud)
我知道这个列表对于这种情况会更理想,但这些数据来自我无法改变的现有结构.也许重新编号键可以解决问题吗?
我在我的脚本中有这个代码来执行霍夫曼编码:
def huffmanEncoding(freqDict):
for key in freqDict.keys():
freqDict[HuffmanTree(value=key)] = freqDict.pop(key)
...
Run Code Online (Sandbox Code Playgroud)
我想要做的是用一个树节点替换字典中的每个键,树节点的值是原始键.HuffmanTree类正常工作.
但是,这段代码有很奇怪的行为.使用调试工具,我发现有时某些键被处理了两次或更多次,这意味着它们首先被转换为树节点,然后再次转换,使用其当前树节点作为新树节点的值.
我用下面显示的代码替换了我的代码:
def huffmanEncoding(freqDict):
keys = list(freqDict.keys())
for key in keys:
freqDict[HuffmanTree(value=key)] = freqDict.pop(key)
Run Code Online (Sandbox Code Playgroud)
现在它正常工作.但有人可以解释为什么我的第一个版本有这么奇怪的行为?如果我想更改字典中的所有键,我应该总是使用第二个版本吗?
我尝试将元组列表转换为字典,但是当我使用 dict() 函数执行此操作时,元素的顺序发生了变化:
l = [('id', 2), ('osm_id', 3), ('sourceid', 4), ('notes', 5), ('ref', 6), ('rtenme', 7), ('ntlclass', 8), ('fclass', 9), ('numlanes', 10), ('srftpe', 11), ('srfcond', 12), ('isseasonal', 13), ('curntprac', 14), ('gnralspeed', 15), ('rdwidthm', 16), ('status', 17), ('bridge', 18), ('iso3', 19), ('country', 20), ('last_updat', 21)]
dict_l = dict(l)
print (dict_l)
{'fclass': 9, 'status': 17, 'isseasonal': 13, 'bridge': 18, 'sourceid': 4, 'country': 20, 'notes': 5, 'rtenme': 7, 'iso3': 19, 'last_updat': 21, 'gnralspeed': 15, 'osm_id': 3, 'srfcond': 12, 'numlanes': 10, 'srftpe': 11, …Run Code Online (Sandbox Code Playgroud) 我正在创建一个函数来在对象(student1)中添加每个数组(作业,测验,测试)的标记.当代码试图添加"Lloyd"时肯定会出现错误.我要检查的数据类型的值的"名",以进行算术运算仅当值的的关键是数量.请建议.
student1 = {
"name": "Lloyd",
"homework": [90, 97, 75, 92],
"quiz": [88, 40, 94],
"test": [75, 90]
}
def eachSubjAverage(std):
for item in std:
total = sum(std[item]) #totalling each marks
std[item].append(total)
average_no = total/(len(std[item])-1) #averaging the marks
std[item].append(average_no)
eachSubjAverage(student1)
Run Code Online (Sandbox Code Playgroud) 我有以下代码:
ex_dict={1:"how",3:"do you",7:"dotoday"}
for key in ex_dict:
string= key," and this is ", ex_dict[key]
print (string)
Run Code Online (Sandbox Code Playgroud)
输出是:
(1, ' and this is ', 'how')
(3, ' and this is ', 'do you')
(7, ' and this is ', 'dotoday')
Run Code Online (Sandbox Code Playgroud)
我的预期输出:
1 and this is how
3 and this is do you
7 and this is dotoday
Run Code Online (Sandbox Code Playgroud)
我似乎无法弄清楚如何摆脱输出中的字典格式.
我试图从列表的每个第 n 个元素创建一个字典,列表的原始索引作为键。例如:
l = [1,2,3,4,5,6,7,8,9]
Run Code Online (Sandbox Code Playgroud)
正在运行
dict(enumerate(l)).items()
Run Code Online (Sandbox Code Playgroud)
给我:
dict_items([(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)])
Run Code Online (Sandbox Code Playgroud)
这就是我想要的。但是,当我现在想从 l 中选择每一个第二个值来执行此操作时,问题就开始了,所以我尝试
dict(enumerate(l[::2])).items()
Run Code Online (Sandbox Code Playgroud)
这给了我
dict_items([(0, 1), (1, 3), (2, 5), (3, 7), (4, 9)])
Run Code Online (Sandbox Code Playgroud)
但我不想那样,我想在制作字典时保留原始索引。做这个的最好方式是什么?
我想要以下输出
dict_items([(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)])
Run Code Online (Sandbox Code Playgroud) 我有一个大小约30000的列表:['aa', 'bb', 'cc', 'dd', ...]从这个列表中,我想构建一个将元素映射到索引的dict,所以结果dict是{'aa': 0, 'bb': 1, 'cc': 2, 'dd': 3, ...}.这是我的代码:
cnt = 0
mp = {}
for name in name_list:
mp[name] = cnt
cnt += 1
return mp
Run Code Online (Sandbox Code Playgroud)
看来我的代码并不简洁有效,那么如何改进呢?
我有一个Json列表,我想从给定的键打印所有键,直到字典结束.但是我写的代码非常复杂.如何以较低的复杂性做到这一点?我正在使用Python 3
dictionary = [{"a": "1"}, {"b": "2"}, {"c": "3"}, {"d": "4"}]
try:
for token in dictionary:
if "b" in list(token.keys())[0]:
new_dict = dictionary[len(list(token.keys())[0]):]
for i in new_dict:
print(new_dict[len(list(i.keys())[0]):])
break
else:
print("Inception")
except Exception as error:
print(str(error))
Run Code Online (Sandbox Code Playgroud)
希望
输入:b
输出:c,d
我的输出:
Inception
[{'c': '3'}, {'d': '4'}]
[{'c': '3'}, {'d': '4'}]
[{'c': '3'}, {'d': '4'}]
Run Code Online (Sandbox Code Playgroud) 我正在解析两个大文件(Gb大小顺序),每个文件包含keys和对应values.一些keys在两个文件之间共享,但具有不同的对应values.对于每个文件,我想写一个新文件keys*和相应的文件values,keys*表示密钥同时出现在file1和file2中.我不关心key输出中的顺序,但绝对应该在两个文件中的顺序相同.
档案1:
key1
value1-1
key2
value1-2
key3
value1-3
Run Code Online (Sandbox Code Playgroud)
文件2:
key1
value2-1
key5
value2-5
key2
value2-2
Run Code Online (Sandbox Code Playgroud)
有效输出将是:
解析文件1:
key1
value1-1
key2
value1-2
Run Code Online (Sandbox Code Playgroud)
解析文件2:
key1
value2-1
key2
value2-2
Run Code Online (Sandbox Code Playgroud)
另一个有效的输出:
解析文件1:
key2
value1-2
key1
value1-1
Run Code Online (Sandbox Code Playgroud)
解析文件2:
key2
value2-2
key1
value2-1
Run Code Online (Sandbox Code Playgroud)
的无效输出(在文件1和文件2不同的顺序键):
解析文件1:
key2
value1-2
key1
value1-1
Run Code Online (Sandbox Code Playgroud)
解析文件2:
key1
value2-1
key2
value2-2
Run Code Online (Sandbox Code Playgroud)
最后一个精度是,值大小远远大于密钥大小.
我想要做的是:
对于每个输入文件,使用与文件中的键对应的键解析并返回a dict(让我们调用它file_index),以及与在输入文件中找到键的偏移量相对应的值.
计算交集
good_keys = file1_index.viewkeys() & file2_index.viewkeys()
Run Code Online (Sandbox Code Playgroud)做一些像(伪代码): …
python ×10
dictionary ×5
python-2.7 ×3
python-3.x ×3
enumeration ×1
eval ×1
iteration ×1
json ×1
object ×1
python-3.5 ×1
random ×1
set ×1
types ×1