Python列表表格化打印求助:zip方法报错及格式异常
Let's break down what's going wrong with your code and fix it step by step:
1. You're misusing zip()
When you wrap each list in square brackets like zip([rounds], [numberOfHits], [score]), you're telling Python to zip three single-element lists (each element being your entire original list). That's why you only get one row of output showing the full lists instead of paired individual elements. You need to pass the lists directly to zip() without the extra brackets.
2. You're calling .join() on None
The print() function returns None (it doesn't produce a string you can modify). Trying to call .join(list) right after print(...) will always throw that AttributeError because you're trying to use a method on a NoneType value. You don't need .join() here anyway—you can build your output string directly with the elements from zip().
3. You're referencing the full lists instead of individual elements
Your string uses rounds, numberOfHits, and score (the full lists) instead of the individual paired values from zip(). That's why your output shows [1, 1] and [6, 4] instead of each round's specific values.
Here's the corrected code (using basic string formatting):
# Example data matching your expected output rounds = [1, 2] numberOfHits = [6, 4] score = ["3 under par.", "1 under par."] # Iterate over paired elements from the three lists for round_num, hits, score_text in zip(rounds, numberOfHits, score): # Build the string using individual elements, not the full lists print("Round [" + str(round_num) + "]: [" + str(hits) + "] shots. " + score_text)
If you prefer cleaner syntax (still Python's built-in features, no external tools), you can use f-strings (available in Python 3.6+):
for round_num, hits, score_text in zip(rounds, numberOfHits, score): print(f"Round [{round_num}]: [{hits}] shots. {score_text}")
Expected Output:
Round [1]: [6] shots. 3 under par. Round [2]: [4] shots. 1 under par.
This fixes all your issues:
zip()now correctly pairs each element from the three lists- We're using the individual paired values to build each line of output
- No more
NoneTypeerror because we removed the invalid.join()call
内容的提问来源于stack exchange,提问作者Amy

