【问题标题】:Using "in" operator compare/convert a string to an int [closed]使用“in”运算符比较/将字符串转换为 int [关闭]
【发布时间】:2018-05-06 08:52:39
【问题描述】:

我需要查找是否在字符串列表中找到整数。

上下文 = ['4', '6', '78']

if category.id in context:

上面的代码不起作用,因为我将 int(category id) 与字符串进行比较。

我不能使用 int(context),因为 context 是一个列表,会报错。

可以将category.id转成字符串,但是会出现不好的情况吗?

使用in 运算符可以将字符串转换为int,或者我需要使用for loop

【问题讨论】:

  • ...你在上下文中尝试过 str(category.id) 吗?
  • @jkm I can convert category.id to string, but can bad situations appear ? 似乎 OP 确实想到了这一点,但不知道这是否是正确的路线?
  • 您认为这两个条目“01”和“001”是相同的还是不同的?
  • str(category.id) in contextcategory.id in map(int, context)
  • 要正确解决这个问题,您需要找出'01'和'001'是否被认为是相同的ID或不同的。除非你澄清这一点,否则继续下去是没有意义的。

标签: python python-3.x for-in-loop


【解决方案1】:

您还可以考虑使用列表推导将context 转换为整数列表。

context_ints = [int(i) for i in context]
if category.id in context_ints:
    ... do stuff ...

如果保证context 是一个可以合理转换为整数的字符串列表,那么这对您来说可能是最安全的方法。

【讨论】:

    【解决方案2】:

    您总是可以将 id 更新为字符串,如下所示:

    class cat():
        def __init__(self, id):
            self.id = id
    
    category = cat(4)
    
    context = ['4', '6', '78']
    
    if str(category.id) in context:
        print('True')
    
    #output
    True
    

    【讨论】:

      猜你喜欢
      • 2014-09-03
      • 1970-01-01
      • 1970-01-01
      • 2019-07-16
      • 2013-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多