如何使用List Comprehension实现首尾为1其余为0的指定长度列表?
Hey there! Let's get that list comprehension working correctly for you. The issue with your current attempt is that the conditional logic is misstructured—you've nested if statements in a way that doesn't match your intended behavior.
First, let's recap what you want: a list where the first and last elements are 1, and everything in between is 0. Your loop-based code already does this perfectly, so we just need to translate that logic directly into a list comprehension.
Correct List Comprehension
Here's the working version that mirrors your loop code:
desired_length = int(input('Enter the desired length: ')) list_ = [1 if x == 0 or x == desired_length - 1 else 0 for x in range(desired_length)] print(list_)
How It Works
This comprehension does exactly what your loop does:
- We iterate over each index
xinrange(desired_length)(just like yourfor i in range(desired_length)loop) - For each index, we check:
- If
xis0(first element) orxisdesired_length - 1(last element), we add1to the list - Otherwise, we add
0
- If
Example Output
If you input 5, the result will be:
[1, 0, 0, 0, 1]
That's all there is to it! This keeps the logic clean and aligned with the loop you already know works.
内容的提问来源于stack exchange,提问作者Alex.Kh

