【问题标题】:Why comparison not working in if condition in python?为什么比较在python中的if条件下不起作用?
【发布时间】:2021-06-02 21:46:24
【问题描述】:

第一季度。给定一个整数数组,如果 6 作为数组中的第一个或最后一个元素出现,则返回 True。数组长度为 1 或更多。

#first_last6([1, 2, 6]) → True
#first_last6([6, 1, 2, 3]) → True
#first_last6([13, 6, 1, 2, 3]) → False

#Code
my_list = []
in_list = list(map(int, input("Enter a multiple value: ").split()))
for num in in_list:
    my_list.append(num)
if (my_list[0:] == 6 or my_list[:-1] == 6):
    print("True")
else:
    print("False")

代码运行良好,但如果条件不起作用而 else 运行良好,例如我们在 else 语句中访问索引“in_list[2]”,它将给出正确的答案。那如果条件不起作用,为什么?

【问题讨论】:

  • 您的索引中不需要:。打印出 my_list[0:]my_list[:-1] 给你调试的内容

标签: python arrays for-loop if-statement arraylist


【解决方案1】:

摆脱:

这是slice 表示法,切片的结果是一个列表,而不是该列表的元素。

my_list = [6, 1, 2, 3]
print(my_list[0:], my_list[:-1]) # slice list
print(my_list[0],  my_list[-1])  # access list item by index

输出:

[6, 1, 2, 3] [6, 1, 2]
6 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 2023-02-09
    相关资源
    最近更新 更多