Python Application Notes: list

Lists are mutable sequences.

1. Basic operations

1.1 The methods of list objects

All of the methods of list objects as follows, excerpt from Python documentation More on Lists.

list.append(x)        # Add an item to the end of the list, i.e., a[len(a):] = [x].
list.extend(L)        # Extend the list by appending all the items in the given list, i.e., a[len(a):] = L.

list.insert(i, x)   # Insert an item at a given position. a.insert(0, x) inserts at the front of the list and a.insert(len(a), x) is equivalent to a.append(x).
list.remove(x)        # Remove the first item from the list whose value is x. It is an error if there is no such item.
list.pop([i])   # Remove the item at the given position in the list, and return it. a.pop() removes and returns the last item in the list. 
list.clear()    # Remove all items from the list, i.e., del a.

list.index(x)   # Return the index in the list of the first item whose value is x. It is an error if there is no such item.
list.count(x)   # Return the number of times x appears in the list.

list.reverse()        # Reverse the elements of the list in place.
list.copy()           # Return a shallow copy of the list, i.e., a.

list.sort(key=None, reverse=False)    #Sort the items of the list in place.

1.2 Iteration

Use the build-in function enumerate to iterate a list with indexes:

L = list()

## regular iteration
for item in L:

## iterate with indexes
enumerate(iterable, start=0) # Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. 

for idx, val in enumerate(L):

Iterate a list in chunks[2] by :

import itertools

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n # iter(o[, sentinel]), Return an iterator object.
    return itertools.izip_longest(*args, fillvalue=fillvalue) # Make an iterator that aggregates elements from each of the iterables. 

## An example
for item in grouper(range(10), 4):
    print(item)

# output
(0, 1, 2, 3)
(4, 5, 6, 7)
(8, 9, None, None)

2. list of lists

A list of lists can be regarded as a table or a two-dimensional array.

2.1 Add one or more columns

Use list comprehensions to add one or more columns to a list of lists:

# Append one columns
new_lists = [row + ['new_column'] for row in lists]

# Insert one column into lists
new_list = [row[:idx] + ['new_column'] + row[idx:] # new row
            for row in lists]

# An example
​>>> lists = [[0, 1, 'a'], [2, 3, 'b'], [4, 5, 'c']]
>>> new_lists = [row[1:] + ['new_column'] + row[1:] for row in lists]
>>> new_lists = [row[:1] + ['new_column'] + row[1:] for row in lists]
>>> print(new_lists)
[[0, 'new_column', 1, 'a'], [2, 'new_column', 3, 'b'], [4, 'new_column', 5, 'c']]

2.2 Sort by specific indexes

# Way 1: Use operator
from operator import itemgetter
lists = [['red', 1], ['blue', 1], ['red', 2], ['blue', 2]]

>>> sorted(lists, key=itemgetter(0, 1))
[['blue', 1], ['blue', 2], ['red', 1], ['red', 2]]

# Way 2: Use lambda
lists = [['red', 1], ['blue', 1], ['red', 2], ['blue', 2]]

>>> sorted(lists, key = lambda x: x[0]) # one attribute
[['blue', 1], ['blue', 2], ['red', 1], ['red', 2]]

>>> sorted(lists, key = lambda x: (x[0], x[1])) # multiple attributes
[['blue', 1], ['blue', 2], ['red', 1], ['red', 2]]

# Way 3: Use the method of list objects: list.sort (in place)
from operator import itemgetter

list.sort(cmp=None, key=None, reverse=False) # Sort the items of the list in place

>>> lists = [['red', 1], ['blue', 1], ['red', 2], ['blue', 2]]
>>> lists.sort(key = itemgetter(0, 1))
>>> print(lists)
[['blue', 1], ['blue', 2], ['red', 1], ['red', 2]]

Further, how to sort multiple attributes with different orderings. I haven’t made it. This might help:

StackOverflow: How to write Python sort key functions for descending values

2.3 Flatten

Flatten a list of lists as a list[3]:

# Way 1: Use list comprehensions
>>> l = [item for sublist in lists for item in sublist]
>>> print(l)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

# Way 2: Use itertools chain, 
>>> import itertools
>>> l = list(itertools.chain(*lists))
>>> print(l)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

2.4 Write to a file

def write_list_of_lists(self, lists, out_file): 
    fp = open(out_file, 'w')
    
    for row in lists:
        s = '\t'.join(str(item) for item in row)
        fp.write(s + '\n')
    
    fp.close()

References:
[1]StackOverflow: Sort a list by multiple attributes?
[2]StackOverflow: What is the most “pythonic” way to iterate over a list in chunks?
[3]StackOverflow: Making a flat list out of list of lists in Python [duplicate]

赞赏

微信赞赏支付宝赞赏

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注