简体   繁体   English

将元组转换为列表时,Python 列表索引超出范围

[英]Python list Index Out of range while Converting Tuple to List

As studying Python I got stuck in a Problem where GeeksforGeeks is telling us that To convert a tuple to List we can use this process variable_name = list(tuple_variable_name) but implementing this process to my sample code doesn't work BTW I am getting the input using sys.stdin.read()在学习 Python 时,我陷入了一个问题,GeeksforGeeks 告诉我们要将元组转换为 List,我们可以使用这个过程variable_name = list(tuple_variable_name)但是在我的示例代码中实现这个过程不起作用顺便说一句我得到了输入使用 sys.stdin.read()

Here is my code which I am trying to run in my Pycharm这是我尝试在 Pycharm 中运行的代码

import sys,ast
input_str = sys.stdin.read()
input_list = ast.literal_eval(input_str)

def my_sort(a1):
    a = list(a1)
    for i in a:
        if (a[i]%5) < (a[i+1]% 5):
            temp = a[i]
            a[i] = a[i+1]
            a[i+1] = temp
    print(a)

my_sort(input_list)

Can anyone help me in clearing out my doubts or Understanding These Concepts任何人都可以帮助我清除疑虑或理解这些概念

I thought it might be worth posting a simple, complete example, since the discussion in the comments lead to a bunch of new information which isn't obvious in the post.我认为可能值得发布一个简单、完整的示例,因为评论中的讨论导致了一堆在帖子中并不明显的新信息。

#str_in = input('Enter the numbers to sort: ')
str_in = '1,9,35,12,13,21,10'

nums = [int(elem) for elem in str_in.split(',')]

sorted_nums = sorted(nums, key=lambda x: x % 5)

print(sorted_nums)

Output:输出:

[35, 10, 1, 21, 12, 13, 9]

Change for i in a to for i in range(len(a)) :for i in a更改for i in a for i in range(len(a))

import sys,ast
input_str = sys.stdin.read()
input_list = ast.literal_eval(input_str)

def my_sort(a1):
    a = list(a1)
    for i in range(len(a)):
        if (a[i]%5) < (a[i+1]% 5):
            temp = a[i]
            a[i] = a[i+1]
            a[i+1] = temp
    print(a)

my_sort(input_list)

for i in a loops over each element in a while for i in range(len(a)) loops over each index. for i in a循环遍历每个元素a时间for i in range(len(a))循环遍历每个索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM