[英]how to print values of dictionary in a list using one line excluding the last element
在我的一项任务中,我被要求执行以下操作:
1 >>> d = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 5}
2 >>> print ________
3 ['one', 'two', 'three', 'four']
如何仅使用上述代码的第2行中的一行代码而不导入任何其他函数来获取第3行中的输出['one', 'two', 'three', 'four']
?
我只能打印出字典的所有值,而不能使用print(list(d.values()))
排除最后一个元素,而我的结果是['one', 'two', 'three', 'four', 5]
如果只想打印字符串字典值(在给定的示例中将不包括最后一个整数值),则可以在print()中使用列表推导,并检查字典值是否为字符串类型:
print([val for val in d.values() if type(val) == str])
如果您有这样的字典,这也将起作用:
d = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 5, 6: 'six'}
print([val for val in d.values() if type(val) == str])
['one', 'two', 'three', 'four', 'six']
一行答案:
list(d.values())[:-1]
d.values()不可下标,因此您需要将其转换为列表。 然后,您可以获得整个列表减去最后一个元素
print (list(d.values())[:-1])
print([v for (k,v) in d.items() if type(v) != int])
输出:
['one', 'two', 'three', 'four']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.