List match
Stargaming
stargaming at gmail.com
Thu Aug 17 11:44:45 EDT 2006
Richie Hindle schrieb:
> [Stephen]
>
>>[...] compare 2 lists and generate a new list that does not copy similar
>>entries. An example below
>>
>>list= ["apple", "banana", "grape"]
>>list2=["orange","banana", "pear"]
>>
>>now I want to compare these lits and generate a third list after
>>comparison
>>
>>list3 would be ["apple", "banana","grape","orange", "pear"]
>
>
> Use sets:
>
>
>>>>from sets import Set as set # For compatibility with Python 2.3
>>>>one = ["apple", "banana", "grape"]
>>>>two = ["orange","banana", "pear"]
>>>>print list(set(one) | set(two))
>
> ['grape', 'apple', 'orange', 'pear', 'banana']
>
Why using Set two times, when you can do it with one call?
>>> list(set(one + two))
According to my benchmarks, this was five times faster than calling it
twice and use |.
There are also a few more good approaches uniquifying lists at
http://www.peterbe.com/plog/uniqifiers-benchmark
Regards,
Stargaming
More information about the Python-list
mailing list