【问题标题】:python list.index('') fails to find string in list if string is in list[0] - why? how do i find it?如果字符串在列表 [0] 中,python list.index('') 无法在列表中找到字符串 - 为什么?我怎么找到它?
【发布时间】:2013-05-10 07:30:22
【问题描述】:

我要疯了吗?

在我的测试中,如果字符串在列表 [0] 中,python list.index('') 无法在列表中找到字符串!!!

为什么?我怎么找到它?

这是我的示例代码:

list1 = ['WTF', '2.09', '\xc2\x80document.write(CurrencyFormat(Currency.convert((209/100),"GBP","EUR")));','0.00', 'Feminised', '6.88', '\xc2\x80document.write(CurrencyFormat(Currency.convert((688/100),"GBP","EUR")));', 'Regular', 'x10', '20.90', '\xc2\x80document.write(CurrencyFormat(Currency.convert((2090/100),"GBP","EUR")));', 'Feminised', 'x12', '82.56', '\xc2\x80document.write(CurrencyFormat(Currency.convert((8256/100),"GBP","EUR")));']
list2 = ['1','2','3','4','5', '1']
if list1.index('0.00'):
    print "I found 0.00 in list 1 but if its in position[0], I cannot find it using index('0.00') - even it appears twice what gives?"
if list2.index('1'):
    print 'weird'
else:
    print 'I did not find 1 in list 2 even thought it is definitely there (twice infact)... WTF?'
print 'I can find it like this but I want to search by string >>> ' + list2[0]
print 'Or like this like this but I want to search by string >>> ' + list2[-1]

这给了我以下结果:

I found 0.00 in list 1 but if its in position[0], I cannot find it using index('0.00') - even it appears twice what gives?
I did not find 1 in list 2 even thought it is definitely there (twice infact)... WTF?
I can find it like this but I want to search by string >>> 1
Or like this like this but I want to search by string >>> 1

我想我一定遗漏了一些非常明显的东西...但无法弄清楚或找到答案...请通过搜索字符串帮助我在 list1 中找到“WTF”或在 list2 中找到“1”... ..

【问题讨论】:

    标签: python list indexing


    【解决方案1】:

    当您执行if list1.index('1') 时,您正在测试该列表中'1' 的索引是否为布尔真。它的索引为零,这是布尔假。所以你的 if 块没有运行。

    如果你想知道它是否在里面,只需if '1' in list1

    【讨论】:

    猜你喜欢
    • 2011-08-31
    • 1970-01-01
    • 2023-04-03
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    相关资源
    最近更新 更多