项目中使用算法

一、查看列表中重复元素

from collections import Counter #引入Counter
a = [1, 2, 3, 3, 4, 4]
b = dict(Counter(a))
print ([key for key,value in b.items() if value > 1]) #只展示重复元素
print ({key:value for key,value in b.items() if value > 1}) #展现重复元素和重复次数

二、查看重复元素所在的位置

l = ['a', 'b', 'c','c', 'd']
[i for i,v in enumerate(l) if v=='c']

三、列表去重

1、set函数

set() 函数创建一个无序不重复元素集 class set([iterable])

lst=[1,3,5,3,4,4,2,9,6,7]
set_lst=set(lst)
if len(set_lst)==len(lst):
   print('列表里的元素互不重复!')
else:
    print('列表里有重复的元素!')

2、创建新列表

确保新列表里不存在重复的元素,然后比较两个列表

lst=[1,3,5,8,9,9,0,0,3,3]
new_list=[]
for i in lst:
    if i not in new_list:
        new_list.append(i)
if len(new_list)==len(lst):
    print('原列表里的元素互不重复!')
else:
    print('原列表里有重复的元素!')

四、从后向前遍历

在对列表进行删除等操作时,若是从前向后操作,列表长度因为元素的删除会变化,影响程序。采用从后向前删除,虽然长度也会变化,但是不影响程序执行

for i in range(len(list_use) - 1, -1, -1):
    if list_use[i]['task_key'] == list_use[i - 1]['task_key']:
        del list_use[i]

五、对列表中的字典元素进行处理

issue_list_tmp=[{'name':'xie','score':12},{'name':'cheng','score':12},{'name':'xie','score':23},{'name':'cheng','score':26}],对其中名称相同的进行分数求和。
思路:对列表遍历,将用户名(字符串)与字典(含用户名与分数)放入新建的列表中,即生成一个元素既有字符串又有字典的列表。

scores_list = []
for issue in issues_list_tmp:
  if issue['name'] in scores_list:
      for ele in scores_list:
          if isinstance(ele, dict) and ele['name'] == issue['name']:
              score_now = ele['score']
              ele['score'] = issue['score'] + score_now
              break
  else:
      dict1 = {'name': issue['name'],'score': issue['score']}
      scores_list.append(dict1)
      scores_list.append(issue['name'])

六、获取目录下所有文件的绝对路径

import os
list_name = [] 
def listdir(path, list_name):  # 传入存储的list
    for file in os.listdir(path):
        file_path = os.path.join(path, file)
        if os.path.isdir(file_path):
            listdir(file_path, list_name)
        else:
            list_name.append(file_path)

原文地址:https://www.cnblogs.com/qev211/p/15320210.html