簡體   English   中英

檢查python中的多個列表中是否存在一個元素並將其附加

[英]Check if an element is present in multiple lists in python and append it

我在 excel csv 文件中有不同的列,我想檢查不同列中的條件,並在滿足條件時將找到的值附加到我的新列表中。

但它不起作用。

這是我的代碼:

# importing module
from pandas import *

# reading CSV file
data = read_csv("test.csv")

# converting column data to list
ext1 = data['ext1'].tolist()
int1 = data['int1'].tolist()
ext2 = data['ext2'].tolist()

ext = []


for i in ext1 or ext2:
    if i >= "2022-03-01":
        ext.append(i)
    else:
        pass

print(*ext, sep="\n")

問題是:

for i in ext1 or ext2:

我認為or是有問題的。

這是我的 csv 文件:

ext1,int1,ext2
2023-01-20,2022-01-20,2022-01-21
2024-01-21,2023-01-22,2024-12-22
2021-01-22,2022-01-22,2022-01-23

該列表應打印:

2023-01-20
2024-01-21
2024-12-22

它只是打印:

2023-01-20
2024-01-21

我不能說我完全理解這個問題,但請嘗試

for i in ext1 + ext2:

ext1 or ext2僅表示“如果不為空則使用ext1 ,否則使用ext2

也去掉else: pass因為它是多余的。

作為旁注,您的整個循環可以在一行中重寫為列表理解:

ext = [i for i in ext1 + ext2 if i >= "2022-03-01"]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM