codingdir logo sitemap sitemap |
Home
PHP
C#
C++
ANDROID
JAVA
JAVASCRIPT
PYTHON

Python: removing first item in each list of a group of lists, starting with the second list


By : , Category : python

Slice your data (this will create a new list in memory though):

newList = [row[0] for row in data[1:]]
ReLated :

this isn't specific to python3 but it works without modification:

>>> from collections import defaultdict
>>> d=defaultdict(list)
>>> for item in a:
...  d[(item['latitude'],item['longtitude'])].append(item)
... 
>>> d
defaultdict(<type 'list'>, {(40.7136948694776, -73.9869100091688): [{'days': "['MON']", 'longtitude': -73.9869100091688, 'signdesc1': 'NO PARKING (SANITATION BROOM SYMBOL) 11AM TO 12:30PM MON & WED', 'to_time': '12:30PM', 'latitude': 40.7136948694776, 'from_time': '11AM'}], (40.7136948694776, -73.9869100091687): [{'days': "['MON']", 'longtitude': -73.9869100091687, 'signdesc1': 'NO PARKING (SANITATION BROOM SYMBOL) 11AM TO 12:30PM MON & THURS', 'to_time': '12:30PM', 'latitude': 40.7136948694776, 'from_time': '11AM'}, {'days': "['MON']", 'longtitude': -73.9869100091687, 'signdesc1': 'NO PARKING (SANITATION BROOM SYMBOL) 11AM TO 12:30PM MON & FRI', 'to_time': '12:30PM', 'latitude': 40.7136948694776, 'from_time': '11AM'}]})
>>> d.values()
[[{'days': "['MON']", 'longtitude': -73.9869100091688, 'signdesc1': 'NO PARKING (SANITATION BROOM SYMBOL) 11AM TO 12:30PM MON & WED', 'to_time': '12:30PM', 'latitude': 40.7136948694776, 'from_time': '11AM'}], [{'days': "['MON']", 'longtitude': -73.9869100091687, 'signdesc1': 'NO PARKING (SANITATION BROOM SYMBOL) 11AM TO 12:30PM MON & THURS', 'to_time': '12:30PM', 'latitude': 40.7136948694776, 'from_time': '11AM'}, {'days': "['MON']", 'longtitude': -73.9869100091687, 'signdesc1': 'NO PARKING (SANITATION BROOM SYMBOL) 11AM TO 12:30PM MON & FRI', 'to_time': '12:30PM', 'latitude': 40.7136948694776, 'from_time': '11AM'}]]

You're overcomplicating this.

What you want to do is: for each value, if it's the same as the last value, just append it to the list of last values; otherwise, create a new list. You can translate that English directly to Python:

new_list = []
for value in old_list:
    if new_list and new_list[-1][0] == value:
        new_list[-1].append(value)
    else:
        new_list.append([value])

There are even simpler ways to do this if you're willing to get a bit more abstract, e.g., by using the grouping functions in itertools. But this should be easy to understand.


If you really need to do this with a while loop, you can translate any for loop into a while loop like this:

for value in iterable:
    do_stuff(value)

iterator = iter(iterable)
while True:
    try:
        value = next(iterator)
    except StopIteration:
        break
    do_stuff(value)

Or, if you know the iterable is a sequence, you can use a slightly simpler while loop:

index = 0
while index < len(sequence):
    value = sequence[index]
    do_stuff(value)
    index += 1

But both of these make your code less readable, less Pythonic, more complicated, less efficient, easier to get wrong, etc.

Using sorted with customer key function:

>>> lstNeedOrder = ['a/b','c/d','f/d','a/e','c/d','a/c']
>>> lst = ['a','b','c']
>>> order = {ch: i for i, ch in enumerate(lst)} # {'a': 0, 'b': 1, 'c': 2}
>>> def sort_key(x):
...     # 'a/b' -> (0, 1), 'c/d' -> (2, 3), ...
...     a, b = x.split('/')
...     return order.get(a, len(lst)), order.get(b, len(lst))
... 
>>> sorted(lstNeedOrder, key=sort_key)
['a/b', 'a/c', 'a/e', 'c/d', 'c/d', 'f/d']
def print_related(xs):
    d = {}
    for (a, b) in xs:
        d.setdefault(a, set()).add(b)
        d.setdefault(b, set()).add(a)
    for k in d:
        print "Items related to %s:" % k
        print "  " + repr(d[k])

This prints the sample input as

Items related to 1:
  set([2, 3, 4, 5])
Items related to 2:
  set([1, 3, 4])
Items related to 3:
  set([1, 2])
Items related to 4:
  set([1, 2])
Items related to 5:
  set([1])

You can use your own function in place of repr to print the sets differently, use a different data structure if you care about repetitions etc.

As per raymonad's comment below, you can also use defaultdict to avoid the two setdefault calls. Making this change and adding a hacky way to print the desired representation of the groups of related items results in

import collections

def print_related(xs):
    d = collections.defaultdict(set)
    for (a, b) in xs:
        d[a].add(b)
        d[b].add(a)
    for k in d:
        print "Items related to %s:" % k
        print "  " + repr(d[k])[5:-2]

Which prints the groups as 2, 3, 4, 5 etc.

Comments


Message :
Login to Add Your Comments .
How to disable registered OpenCL platforms on Windows?
Is Observable broken in Angular 2 Beta 3?
Cross-thread operation not valid when using Invoke
How to pass an IEnumerable or queryable list of properties from Controller to View
Finding numbers after a certain keyword using Python
Pocketsphinx recognizes random phrases in a silence
Passing non-thread-safe objects through thread-safe containers
React scroll nav
BizTalk WCF-BasicHttp Adapter does not allow Empty string for Service Certificate Props
Why property ''cause" of Exception is repeating forever?
Privacy Policy 2017 © codingdir.com All Rights Reserved .