【问题标题】:checking if for loop variable is at last index of string (not variable == string[index_Integer])检查 for 循环变量是否在字符串的最后索引处(不是变量 == 字符串 [index_Integer])
【发布时间】:2012-04-22 03:53:03
【问题描述】:

我觉得我在 for 循环和用户输入方面做错了

每当我执行for循环时,我确实相信for循环中的局部变量在列表中只有一个条目

list[index_int] #returns value of the indexed entry in the list
user_input = "1234"
user_input[-1] >>> 4


    def print_numbers(n):
    for entry in n:
        if entry == "1":
            if (entry == n[-1]):
                print "E"
            else:
                print entry + "s,",
        elif entry == "0":
            if (entry == n[-1]):
                print "X"
            else:
                print entry + "X,",
        else:
            if (entry == n[-1]): #applies if entry is equal to the value of user input       at index value of (-1), which I do not want
                print entry + "L"
            else:
                print entry + "s,",            
user_input = raw_input()
if user_input.isdigit():
    print_numbers(user_input)
else:
    print user_input

当我想放下 101 或 212 时,我得到了这些

Intention -> 1s, X, E
Result:
E
X, E

Intention -> 2s, 1s, 2L
Result:
2L 
1s, 2L

我确实认为原因是在 for 循环期间,每个变量在其自己的列表中只有一个元素。

有没有办法检查 for 循环是否在列表(字符串)的最后一个索引位置(变量不等于字符串索引的值,即 entry == n[-1])?

【问题讨论】:

    标签: python if-statement for-loop iteration


    【解决方案1】:

    您正在寻找enumerate()。还有一点,但你应该能够弄清楚那部分。

    【讨论】:

    • 谢谢!我了解到我可以通过使用列表拆分来制作单独的字符串 :list[i:j] 并分配这样的新字符串:ones = n[len(n)-1:] and other_digits = n[:len(n )-1] 并且我将它们中的每一个都放在各自函数中的 for 循环中,但感谢您的帮助
    猜你喜欢
    • 2016-10-03
    • 1970-01-01
    • 2011-05-02
    • 2011-12-06
    • 1970-01-01
    • 2015-02-04
    • 2020-05-28
    • 1970-01-01
    相关资源
    最近更新 更多