在 CPython 3.6 中获取字典中的第一个和第二个值
Get first and second values in dictionary in CPython 3.6
既然字典在python3.6中是有序的,那肯定有办法只用两行就可以得到字典的第一个和第二个值。现在,我必须使用 7 行来完成此操作:
for key, value in class_sent.items():
i += 1
if i == 1:
first_sent = value
elif i == 2:
second_sent = value
我也试过:
first_sent = next(iter(class_sent))
second_sent = next(iter(class_sent))
但在那种情况下 second_sent 等于 first_sent。如果有人知道如何在尽可能少的行中获取字典中的第一个和第二个值,我将不胜感激。
现在Python只保证**kwargs
和class属性的顺序被保留。
考虑到您正在使用的 Python 的实现保证了您可以执行此行为。
- 使用
itertools.islice
.
>>> from itertools import islice
>>> dct = {'a': 1, 'b': 2, 'c': 3}
>>> first, second = islice(dct.values(), 2)
>>> first, second
(1, 2)
- 使用
iter()
.
>>> it = iter(dct.values())
>>> first, second = next(it), next(it)
>>> first, second
(1, 2)
- 使用extended iterable unpacking(也会导致对其他值进行不必要的解包):
>>> first, second, *_ = dct.values()
>>> first, second
(1, 2)
这可行:
first_sent, second_sent = list(class_sent.values())[:2]
既然字典在python3.6中是有序的,那肯定有办法只用两行就可以得到字典的第一个和第二个值。现在,我必须使用 7 行来完成此操作:
for key, value in class_sent.items():
i += 1
if i == 1:
first_sent = value
elif i == 2:
second_sent = value
我也试过:
first_sent = next(iter(class_sent))
second_sent = next(iter(class_sent))
但在那种情况下 second_sent 等于 first_sent。如果有人知道如何在尽可能少的行中获取字典中的第一个和第二个值,我将不胜感激。
现在Python只保证**kwargs
和class属性的顺序被保留。
考虑到您正在使用的 Python 的实现保证了您可以执行此行为。
- 使用
itertools.islice
.
>>> from itertools import islice
>>> dct = {'a': 1, 'b': 2, 'c': 3}
>>> first, second = islice(dct.values(), 2)
>>> first, second
(1, 2)
- 使用
iter()
.
>>> it = iter(dct.values())
>>> first, second = next(it), next(it)
>>> first, second
(1, 2)
- 使用extended iterable unpacking(也会导致对其他值进行不必要的解包):
>>> first, second, *_ = dct.values()
>>> first, second
(1, 2)
这可行:
first_sent, second_sent = list(class_sent.values())[:2]