ค้นหาหุ้นที่มีราคาสูงสุด
เมธอดที่มีประโยชน์อีกตัวหนึ่งของลิสต์คือ .index() ซึ่งจะคืนค่า index ของ element ที่ระบุ ตัวอย่างเช่น หากต้องการหา index ของ 2 ใน x ให้เขียนดังนี้
x = [1, 2, 3, 4]
x.index(2)
1
จากนั้นนำผลลัพธ์ที่ได้ไปใช้เลือกข้อมูลจากลิสต์อื่น ซึ่งเป็นสิ่งที่จะทำในแบบฝึกหัดนี้
ลิสต์ prices และ names พร้อมใช้งานแล้วใน workspace ของคุณ
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python เบื้องต้นสำหรับการเงิน
คำแนะนำการฝึกหัด
- หา index ของ
max_priceในลิสต์prices - นำ index ที่ได้ไปใช้กับลิสต์
namesเพื่อระบุบริษัทที่มีราคาหุ้นสูงสุด
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Do not modify this
max_price = max(prices)
# Identify index of max price
max_index = prices.____(____)
# Identify the name of the company with max price
max_stock_name = names[____]
# Fill in the blanks
print('The largest stock price is associated with ' + max_stock_name + ' and is $' + str(max_price) + '.')