简体   繁体   English

字典理解:更改列表值中的最后一项

[英]Dictionary comprehension: change the last item in a list value

I have a Python dictionary mapping strings to lists of strings. 我有一个Python字典,将字符串映射到字符串列表。

  • I want to change the last item of each list to uppercase using a dictionary comprehension 我想使用字典理解将每个列表的最后一项更改为大写

Eg for this example 例如这个例子

dd = {'cc': ['aa', 'UU', 'zzzzzzz'], 't': ['aa', 'uu', 'ZZZZZZ']}

I want this: 我要这个:

{'cc': ['aa', 'UU', 'ZZZZZZZ'], 't': ['aa', 'uu', 'ZZZZZZ']} # note the last item in the first list 

I thought I could just re-assign the last item via indexing and tried variations of this 我以为我可以通过索引重新分配最后一个项目,并尝试对此进行变体

{k: (v[-1] = v[-1].upper()) for k,v in dd.viewitems()} 
# --> returns syntax error
# or this, which returns None:
{k: v[:-1].append(v[-1].upper()) for k,v in dd.viewitems()}
#the below works but I don't like it
{k: [i if not v.index(i) == len(v)-1 else i.upper() for i in v] for k,v in dd.viewitems()}

I can't get it to work w/out a dirty list comprehension. 我无法通过脏列表理解来工作。

  • Is there a good way to do this? 有什么好方法吗?

(I am on Py 2 though through no fault of my own) (尽管我自己没有错,但我在Py 2上)

Thanks! 谢谢!

Use a simple for loop: 使用简单的for循环:

dd = {'cc': ['aa', 'UU', 'zzzzzzz'], 't': ['aa', 'uu', 'ZZZZZZ']}

for v in dd.itervalues():
    v[-1] = v[-1].upper()

print dd

{'cc': ['aa', 'UU', 'ZZZZZZZ'],
 't': ['aa', 'uu', 'ZZZZZZ']}

A dictionary comprehension cannot contain assignments, and so is inappropriate for the logic you are attempting to apply. 词典理解不能包含分配,因此对于您尝试应用的逻辑是不合适的。

You can use unpacking: 您可以使用拆包:

dd = {'cc': ['aa', 'UU', 'zzzzzzz'], 't': ['aa', 'uu', 'ZZZZZZ']}
new_d = {a:[c, d, e.upper()] for a, [c, d, e] in dd.items()}

Output: 输出:

{'cc': ['aa', 'UU', 'ZZZZZZZ'], 't': ['aa', 'uu', 'ZZZZZZ']}

However, for lists with arbitrary numbers of elements, you can use negative indexing: 但是,对于具有任意数量元素的列表,可以使用负索引:

new_d = {a:b[:-1]+[b[-1].upper()] for a, b in dd.items()}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM