Python列表中去重的多种方法
<p>怎么快速的对列表进行去重呢,去重之后原来的顺序会不会改变呢?</p><h4 id="去重之后顺序会改变">去重之后顺序会改变</h4>
<p><strong>set去重</strong></p>
<h1 id="列表去重改变原列表的顺序了">列表去重改变原列表的顺序了</h1>
<pre><code class="language-python">l1 =
l2 = list(set(l1))
print(l2) #
</code></pre>
<p>但是,可以通过列表中索引(index)的方法保证去重后的顺序不变。</p>
<pre><code class="language-python">l1 =
l2 = list(set(l1))
l2.sort(key=l1.index)
print(l2) #
itertools.groupby
</code></pre>
<p><strong>itertools.groupby</strong></p>
<pre><code class="language-python">import itertools
l1 =
l1.sort()
l = []
it = itertools.groupby(l1)
for k,g in it:
l.append(k)
print(l) #
</code></pre>
<p><strong>fromkeys</strong></p>
<pre><code class="language-python">l1 =
t = list({}.fromkeys(l1).keys())
# 解决顺序问题
t.sort(key=l1.index)
print(t) #
</code></pre>
<p><strong>通过删除索引</strong></p>
<pre><code class="language-python">l1 =
t = l1[:]
for i in l1:
while t.count(i) >1:
del t
# 解决顺序问题
t.sort(key=l1.index)
print(t) #
</code></pre>
<h4 id="去重不改变顺序">去重不改变顺序</h4>
<p><strong>建立新列表[]</strong></p>
<pre><code class="language-python">l1 =
new_l1 = []
for i in l1:
if i not in new_l1:
new_l1.append(i)
print(new_l1) #
</code></pre>
<p><strong>reduce方法</strong></p>
<pre><code class="language-python">from functools import reduce
l1 =
func = lambda x,y:x if y in x else x +
print(reduce(func,[[],]+l1)) #
</code></pre><br><br>
来源:https://www.cnblogs.com/xxpythonxx/p/12181224.html
頁:
[1]