You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用List Comprehension实现首尾为1其余为0的指定长度列表?

Fixing Your List Comprehension for a List with 1s at First/Last Positions

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 x in range(desired_length) (just like your for i in range(desired_length) loop)
  • For each index, we check:
    • If x is 0 (first element) or x is desired_length - 1 (last element), we add 1 to the list
    • Otherwise, we add 0

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:58:29