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('') - 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]