list, set操作

def union_list(l1, l2):
    result = []
    if not l1:
        result.extend(l2)
        return result
    if not l2:
        result.extend(l1)
        return result
    result.extend(l1)
    for i in set(l1+l2):
        if i not in l1:
            result.append(i)
    return result

set(l1+l2) 也可以达到以上目的,但是会重新排序。上述程序保留l1的顺序。

 

set 的操作:

联合(Union) 交集(Intersection) 差集(Difference)

a | b  # union

a & b # intersection

a ^ b # in a or in b but not in a & b   equals   a.symmetric_difference(b)

set的减法与被减数相关,等同set.difference(): all elements that are in this set but not the others.

 

>>m = set('arwb+tU')
>>m
set(['a', 'b', '+', 'r', 'U', 't', 'w'])
>>set('r') - m
set([])  # False
>> set('2') - m
set([2])  # True

>>l = [1, 2, 3]
>>ll = [2, 4, 6]
>> set(l) - set(ll)
set([2])

>> ll = [4, 6]
>> set(l) - set(ll)
set([1, 2, 3])

 

去掉 list 中的重复元素:

{}.fromkeys(list).keys()
or
set(list)

遍历

for i in alist:
    print i

for index, item in enumerate(alist):
    print index, item

 list 加法

alist = [2, 3]
s = ["dfjo"]+alist  
>>s
['dfjo', 2, 3]

 

posted @ 2015-04-09 17:27  道以万计  阅读(344)  评论(0编辑  收藏  举报