list-comprehension

Sum nested key values of dict

橙三吉。 提交于 2020-01-16 07:06:29
问题 This is my sample dictionary in Python 2.7: sample = {'T1': {'P1': 20, 'P2': 100}, 'T2': {'P1': 60, 'P2': 50}} I am trying to sum up all the values with the key 'P1' and 'P2' to get a result like this: reqResult = [80,150] How would I go about this? Many thanks. 回答1: You can use >>> d = {'T1': {'P1': 20, 'P2': 100}, 'T2': {'P1': 60, 'P2': 50}} >>> map(sum, zip(*[x.values() for x in d.values()])) [150, 80] This will first compute the innner dicts, than take out their values and zip them

Python: find sequential change in one member of list pairs, report other

心已入冬 提交于 2020-01-16 05:14:13
问题 There must be a simpler, more pythonic way of doing this. Given this list of pairs: pp = [('a',1),('b',1),('c',1),('d',2),('e',2)] How do I most easily find the first item in adjacent pairs where the second item changes (here, from 1 to 2). Thus I'm looking for ['c','d']. Assume there will only be one change in pair[1] for the entire list, but that it may be a string. This code works but seems excruciatingly long and cumbersome. for i, pair in enumerate(pp): if i == 0: pInitial = pair[0]

Weird lambda behaviour in list comprehension [duplicate]

核能气质少年 提交于 2020-01-14 13:52:07
问题 This question already has answers here : Weird behavior: Lambda inside list comprehension (6 answers) Closed 5 years ago . I'm playing with lambda functions inside of list comprehension, and found some weird behaviour x = [(lambda x: i) for i in range(3)] print(x[0](0)) #print 2 instead of 0 print(x[1](0)) #print 2 instead of 1 print(x[2](0)) #print 2 Can someone explain why the result is not that I expect? 回答1: lambda s bind variables themselves, not the values that they had. i is changed to

Python: Filter positive and negative integers from string

☆樱花仙子☆ 提交于 2020-01-13 07:29:07
问题 Python 3: Given a string (an equation), return a list of positive and negative integers. I've tried various regex and list comprehension solutions to no avail. Given an equation 4+3x or -5+2y or -7y-2x Returns: [4,3], [-5,2], [-7,-2] input str = '-7y-2x' output my_list = [-7, -2] 回答1: Simple solution using re.findall function: import re s = '-5+2y' result = [int(d) for d in re.findall(r'-?\d+', s)] print(result) The output: [-5, 2] -?\d+ - matches positive and negative integers Raw string

LIst Comprehensions: References to the Components

一笑奈何 提交于 2020-01-12 07:31:12
问题 In sum: I need to write a List Comprehension in which i refer to list that is being created by the List Comprehension. This might not be something you need to do every day, but i don't think it's unusual either. Maybe there's no answer here--still, please don't tell me i ought to use a for loop. That might be correct, but it's not helpful. The reason is the problem domain: this line of code is part of an ETL module, so performance is relevant, and so is the need to avoid creating a temporary

How do I merge a 2D array in Python into one string with List Comprehension?

大憨熊 提交于 2020-01-12 02:57:11
问题 List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers. Say, I have a 2D list: li = [[0,1,2],[3,4,5],[6,7,8]] I would like to merge this either into one long list li2 = [0,1,2,3,4,5,6,7,8] or into a string with separators: s = "0,1,2,3,4,5,6,7,8" Really, I'd like to know how to do both. 回答1: Like so: [ item for innerlist in outerlist for item in innerlist ] Turning that directly into a string with separators: ','.join(str

List comprehension version of “extend” [duplicate]

依然范特西╮ 提交于 2020-01-11 10:08:50
问题 This question already has answers here : How to use list comprehension with .extend list method? [duplicate] (2 answers) How can I use a list comprehension to extend a list in python? [duplicate] (6 answers) Python: How to extend or append multiple elements in list comprehension format? (2 answers) Closed 2 years ago . Is there a 1-liner equivalent (using list comprehension) for the following: a = [] for i in range(6): a.extend(((-i,i,0,2),(-i-1,i,0,6))) a = tuple(a) I was thinking something

How to recursively query in django efficiently?

喜夏-厌秋 提交于 2020-01-11 05:09:33
问题 I have a model, which looks like: class StaffMember(models.Model): id = models.OneToOneField(to=User, unique=True, primary_key=True, related_name='staff_member') supervisor = models.ForeignKey(to='self', null=True, blank=True, related_name='team_members') My current hierarchy of team is designed in such a way that there is let's say an Admin (who is at the top most point of hierarchy). Now, let's say 3 people (A, B, C) report to Admin and each one of A, B and C have their own team reporting

How to use list comprehension to add an element to copies of a dictionary?

青春壹個敷衍的年華 提交于 2020-01-10 10:10:05
问题 given: template = {'a': 'b', 'c': 'd'} add = ['e', 'f'] k = 'z' I want to use list comprehension to generate [{'a': 'b', 'c': 'd', 'z': 'e'}, {'a': 'b', 'c': 'd', 'z': 'f'}] I know I can do this: out = [] for v in add: t = template.copy() t[k] = v out.append(t) but it is a little verbose and has no advantage over what I'm trying to replace. This slightly more general question on merging dictionaries is somewhat related but more or less says don't. 回答1: [dict(template,z=value) for value in add

How to use list comprehension to add an element to copies of a dictionary?

让人想犯罪 __ 提交于 2020-01-10 10:09:26
问题 given: template = {'a': 'b', 'c': 'd'} add = ['e', 'f'] k = 'z' I want to use list comprehension to generate [{'a': 'b', 'c': 'd', 'z': 'e'}, {'a': 'b', 'c': 'd', 'z': 'f'}] I know I can do this: out = [] for v in add: t = template.copy() t[k] = v out.append(t) but it is a little verbose and has no advantage over what I'm trying to replace. This slightly more general question on merging dictionaries is somewhat related but more or less says don't. 回答1: [dict(template,z=value) for value in add