春江暮客

春江暮客的个人学习分享网站

python查找两个数组公有值

2019-03-08 技术
python查找两个数组公有值

生活中经常碰到需要获取两数组公有值,那么python如何优雅获取两个数组之间的公有值,这里提供多种简单实用方法。

不过在真正写代码时,除了“能不能求交集”,通常还要关心两件事:结果是否去重,以及是否保留原列表顺序。下面几种方法的差别主要就在这里。

1.使用set元组的 &

list1 = [1,2,3,4,5,6,7]
list2 = [1,3, 5, 7, 9]
set(list1) & set(list2)
#{1, 3, 5, 7}

这种写法最短,但结果是 set,因此不会保留原来列表顺序,而且会自动去重。

2.使用set元组的intersection交集

list1 = [1,2,3,4,5,6,7]
list2 = [1,3, 5, 7, 9]
set(list1).intersection(list2)
#{1, 3, 5, 7}

本质上和前一种方法一样,也是集合交集,特点同样是无序且去重。

3.暴力查询list元素是否在第二个list中

list1 = [1,2,3,4,5,6,7]
list2 = [1,3, 5, 7, 9]
[element for element in list1 if element in list2]
   # [1, 3, 5, 7]

如果你希望结果保持 list1 原本的顺序,这种列表推导式通常更直观。

4.实用set元组的减法

list1 = [1,2,3,4,5,6,7]
list2 = [1,3, 5, 7, 9]
set(list1) - (set(list1)-set(list2))
#{1, 3, 5, 7}

这个写法同样能得到交集,但可读性通常不如前两种 set 写法。

什么时候用哪种方法

  • 只关心交集内容,不关心顺序,也不需要保留重复值:优先用 set(list1) & set(list2)
  • 想保留 list1 的顺序:优先用列表推导式
  • 如果列表很大,且还想保留顺序,可以先把第二个列表转成集合再判断成员关系
set2 = set(list2)
[element for element in list1 if element in set2]

标签

1024 12306 2fa ablang adsense agents.md ai ai-agent ai-agents ai-seo algorithm amp antibodies apparmor argparse automation backup bash batch-processing binarycif bioinformatics biopython blockchain boltz bootstrapping boxes bubblewrap c-index cca cdn chatgpt checkpoint cli cloudflare codex cofoldarena concurrency configparser configuration copy cprofile cpu监控 cron csv cuda curl data-leakage data-processing data-quality data-validation datascience datavisualization datetime debugging decimal deployment desktop-app devtools difflib disk-space disown dns docker dovecot download electron encoding esm esm2 esm3 esmc esmfold2 etag evaluation faceswap fasta fastmcp faulthandler ffmpeg file-descriptors file-io file-management filenames files flashppi flask folium frontend game generator git github-actions google google-research gpt-6.1-sol grep gzip harness heapq hls html http hugo imports indexnow ipaddress jailbreak javascript jev json jsonl just k-means kaggle langfuse leecode linux list litellm llm llms.txt logging logs lollipop lsof m3u8 machine-learning macos manacher matplotlib mcp memory mirror mmcif model-evaluation monitoring mp3 mp4 mpnn multiomics multiprocessing mutation mysql nanobert nanobodies networking networkx nginx normalize numpy ollama omegatherm pandas password pathlib pdb pep-723 performance permissions phaser pillow pip postfix preprocessing print prompt-engineering protein-alignment protein-design protein-embeddings protein-interactions protein-language-models protein-stability protein-structure proxy pydantic pyecharts pyqt python python3 r raincloud reproducibility requests reservoir-sampling rfoptimization rg ripgrep rosettafold3 roundcube rrsi rsi rsync s-tui sampling scale scikit-learn scrapy screen seaborn security selenium seo sequence-identity sha256 shell signals sitemap sklearn socket solana somaticsignatures sorting spl sqlite ssh standardize static-site subprocess symlink sysadmin system-one tarfile tcp tempfile tensorflow tkinter tls toml totp tracemalloc tron tronpy troubleshooting turtle typesafe-ai ubuntu unicode urllib usdt utf-8 uv venv vhhbert vite web-tools webp wordcloud wordpress workflow xml yaml zipfile zoneinfo 后台 寓言 概率 经济 贸易 迅雷解析 钱包

友情链接

其它