Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python – แทนที่ Element ใน List ตามการเปรียบเทียบกับ Key (Replace by Comparison)

ภาพรวม

เปรียบเทียบแต่ละ element ใน list กับ key ถ้ามากกว่า key ให้แทนที่ด้วย high value ถ้าน้อยกว่าหรือเท่ากับให้แทนที่ด้วย low value

ตัวอย่างโค้ด


my_list = [32, 37, 44, 38, 92, 61, 28, 92, 20]
my_key = 32
low, high = 2, 9

print("The list is:", my_list)
print("The key is:", my_key)

my_result = [high if x > my_key else low for x in my_list]

print("The resultant list is:", my_result)

ผลลัพธ์

The list is: [32, 37, 44, 38, 92, 61, 28, 92, 20]
The key is: 32
The resultant list is: [2, 9, 9, 9, 9, 9, 2, 9, 2]

คำอธิบาย

  • 32 <= 32 -> low (2)
  • 37, 44, 38, 92, 61, 92 > 32 -> high (9)
  • 28, 20 <= 32 -> low (2)

ขยาย: หลายช่วง (Binning/Discretization)


def bin_value(x, bins):
    """bins = [(threshold, label), ...] เรียงจากน้อยไปมาก"""
    for threshold, label in bins:
        if x <= threshold:
            return label
    return bins[-1][1]

bins = [(30, 'Low'), (60, 'Medium'), (float('inf'), 'High')]
result = [bin_value(x, bins) for x in my_list]
# ['Low', 'Medium', 'Medium', 'Medium', 'High', 'High', 'Low', 'High', 'Low']

Pandas cut/qcut


import pandas as pd
s = pd.Series(my_list)
pd.cut(s, bins=[-float('inf'), 32, 60, float('inf')], labels=['Low', 'Medium', 'High'])