P: 50
|
Can anyone suggest a better way of returning the values in a dictionary as a single list. I have the following, but it uses a nested loop, not sure if there is a more efficient way. -
>>> d['a']= [(45,6)]
-
>>> d['a'].append((56,4))
-
>>> d['a']
-
[(45, 6), (56, 4)]
-
>>> s =[]
-
>>> for i, j in enumerate(d['a']):
-
... for k, l in enumerate(j):
-
... s.append(l)
-
...
-
>>> s
-
[45, 6, 56, 4]
-
>>>
-
thanks
| |
Share this Question
Expert 100+
P: 844
|
Can anyone suggest a better way of returning the values in a dictionary as a single list. I have the following, but it uses a nested loop, not sure if there is a more efficient way. -
>>> d['a']= [(45,6)]
-
>>> d['a'].append((56,4))
-
>>> d['a']
-
[(45, 6), (56, 4)]
-
>>> s =[]
-
>>> for i, j in enumerate(d['a']):
-
... for k, l in enumerate(j):
-
... s.append(l)
-
...
-
>>> s
-
[45, 6, 56, 4]
-
>>>
-
thanks
-
s = [value for tup in d['a'] for value in tup]
-
Hope that helps.
| | Expert 5K+
P: 6,596
|
Can anyone suggest a better way of returning the values in a dictionary as a single list. I have the following, but it uses a nested loop, not sure if there is a more efficient way. -
>>> d['a']= [(45,6)]
-
>>> d['a'].append((56,4))
-
>>> d['a']
-
[(45, 6), (56, 4)]
-
>>> s =[]
-
>>> for i, j in enumerate(d['a']):
-
... for k, l in enumerate(j):
-
... s.append(l)
-
...
-
>>> s
-
[45, 6, 56, 4]
-
>>>
-
thanks
-
>>> aList = [(45, 6), (56, 4)]
-
>>> newList = []
-
>>> for tup in aList:
-
... newList.extend(tup)
-
...
-
>>> newList
-
[45, 6, 56, 4]
-
>>>
| |
P: 50
|
Sweet, thanks. Much better!
| | Expert 5K+
P: 6,596
|
Sweet, thanks. Much better!
You did see mine, right? One minute apart, maybe you were posting while I was.
| | Expert 100+
P: 844
| -
>>> aList = [(45, 6), (56, 4)]
-
>>> newList = []
-
>>> for tup in aList:
-
... newList.extend(tup)
-
...
-
>>> newList
-
[45, 6, 56, 4]
-
>>>
Just for fun, you could do that with map: -
>>> aList = [(45, 6), (56, 4)]
-
>>> newList = []
-
>>> map(newList.extend, aList)
-
>>> newList
-
[45, 6, 56, 4]
-
| | Expert 5K+
P: 6,596
|
Just for fun, you could do that with map: -
>>> aList = [(45, 6), (56, 4)]
-
>>> newList = []
-
>>> map(newList.extend, aList)
-
>>> newList
-
[45, 6, 56, 4]
-
Bonus points to you, my friend! Two lines in one; very nicely done.
| | | | Question stats - viewed: 1444
- replies: 6
- date asked: Aug 15 '07
|