Python报错TypeError: 'float'不可迭代,求嵌套列表代码修正
Fixing
TypeError: 'float' object is not iterable + Correctly Finding the Second-Lowest Scoring Students Let's walk through what's broken in your code and how to fix it to meet your goal of printing the names of students with the second-lowest physics score.
First: Why the TypeError?
Your nested list comprehension l=[[x,y] for x in name for y in score if (max(score)-y) > 0] is triggering the error. Here's the root cause:
scoreis a single float value (fromfloat(input())), not a list or iterable sequence. Trying to loopfor y in scoretells Python to iterate over a float, which it can't do—hence the'float' object is not iterablemessage.- On top of that, your initial loop doesn't save all student data! You're overwriting
nameandscoreeach iteration, so by the end, you only have the last student's information stored.
Other Logic Gaps in the Original Code
- The list comprehension
lis trying to do something unclear (comparing to a "max score" that's just the last student's score) instead of collecting all student records. - The loop to find
maxis irrelevant to your goal—you need the second-lowest score, not the highest. print(m.sort())will printNonebecausesort()modifies the list in-place and returns nothing.
Fixed Code to Meet Your Requirement
Here's the corrected version that properly collects data, finds the second-lowest score, and prints the corresponding student names sorted alphabetically:
if __name__ == '__main__': students = [] # Step 1: Collect all student names and scores for _ in range(int(input())): name = input().strip() score = float(input().strip()) students.append([name, score]) # Step 2: Get unique scores, sort them, pick the second lowest unique_scores = sorted({s[1] for s in students}) second_lowest = unique_scores[1] # Step 3: Filter students with the second lowest score, sort their names result = sorted([s[0] for s in students if s[1] == second_lowest]) # Step 4: Print each name on a new line for name in result: print(name)
Breakdown of the Fixed Code
- Collecting Data: We use a
studentslist to store every [name, score] pair as we input them—no more overwriting values. - Finding Second-Lowest Score: We create a set of scores to remove duplicates, sort the unique scores in ascending order, and grab the second element (index 1).
- Filtering and Sorting Names: We filter all students with the second-lowest score, sort their names alphabetically, then print each one individually.
Example Output
If your input is:
5 Harry 37.21 Berry 37.21 Tina 37.2 Akriti 41 Harsh 39
The output will be:
Berry Harry
内容的提问来源于stack exchange,提问作者Kartheek Gade
相关产品推荐
相关产品推荐

