【问题标题】:checking next and previous indexes检查下一个和上一个索引
【发布时间】:2019-12-12 09:18:10
【问题描述】:

我正在尝试遍历每个索引并检查它是否大于下一个索引,但我想不出任何关于如何做到这一点的想法。我尝试使用 rangeenumerate 函数,但没有奏效,非常感谢您的帮助。这是我当前的代码:

user_input = input("Anything: ")
user_input = user_input.split(",")
arrayList = [int(i) for i in user_input]
test = []

for the_index, the_item in enumerate(arrayList):

这是我之前尝试过的

user_input = input("Anything: ")
user_input = user_input.split(",")
arrayList = [int(i) for i in user_input]
first_numbers = []
second_numbers = []
finalList = []

for i in arrayList:
    the_index = arrayList.index(i)
    if the_index % 2 != 0:
        first_numbers.append(i)
    if the_index % 2 == 0:
        second_numbers.append(i)

first_numbers.append(second_numbers)

【问题讨论】:

  • 你能添加你的输入和预期输出吗
  • 您能否澄清一下:您想逐步检查一个list 的数字并将每个元素与前一个和下一个元素进行比较?根据比较的结果应该发生什么?
  • 正是如此,输出应该是大于它们旁边的数字的数字,
  • 输出应该是这样的:如果用户输入是一个列表:1,3,2,4,11,7,9,5 输出:3 > 2, 11 > 7, 9 > 5 ,

标签: python python-3.x list indexing


【解决方案1】:

不确定我是否明白这一点,但如果您想知道用户的输入是否更大 / smaller比之前的选择,您可以这样做:

这可能不是最短的方法,但这是一个动态的 sn-p,您可以在其中决定尽可能多地询问您希望用户回答的输入:

user_choice = input('Choose some numbers: ')
user_choice_listed = user_choice.split(',')

marked_choice = None # Uninitialized integer that would be assigned in the future
for t in user_choice_listed:

    converted_t = int(t)

    if marked_choice != None and marked_choice < converted_t:
        print('{0} is Bigger than your previous choice, it was {1}'.format(t,marked_choice))
    elif marked_choice != None and marked_choice > converted_t:
        print('{0} is Smaller than your previous choice, it was {1}'.format(t,marked_choice))
    elif marked_choice == None:
        print('This is your first Choice, nothing to compare with!')

    marked_choice = converted_t # this is marking the previous answer of the user

注意:您可以添加一行来处理前一个与当前选择等于的位置。

输出:

Choose some numbers: 1,3,5 # My Input

This is your first Choice, nothing to compare with!
3 is Bigger than your previous choice, it was 1
5 is Bigger than your previous choice, it was 3

【讨论】:

  • 了解您的代码,非常感谢,但这不是我想要的。我想要做的是从用户那里获取整数列表并遍历每个数字并检查它是否大于下一个。所以这是一个用户输入:[1,6,5,8,7,11,9] 我必须得到(6 大于 5,8 大于 7,11 大于 9)作为输出跨度>
  • 嘿但丁,请看我的编辑。这一次,输入接受除以逗号 (,) 的数字列表,然后转换为整数列表。这会奏效。
  • 非常感谢您的代码和帮助,我真的很感激。非常感谢你;
  • 对了,你能解释一下这里的marked_choice是做什么的吗?
  • 是的,我将每个整数存储在标记选择中所有代码执行之后,并且在第二次运行中,标记选择未存储尚未与下一个整数,所以它记住前一个。显然,它必须在循环的外部初始化为None。因为你不能将你的第一个整数与前一个整数进行比较,因为没有前一个整数,所以我通过输出这是第一个整数来处理它。
【解决方案2】:

通过索引循环它?

for i in range(len(arrayList)):
     if arrayList[i] > arrayList[i + 1]:
         //enter code here

【讨论】:

  • 在这种情况下,我将超出索引范围错误:/
  • for i in range(len(arrayList)-1): 如果您将一项与下一项进行比较,这将停止索引超出范围错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多