【问题标题】:comparing numbers in 2 string A and B比较 2 个字符串 A 和 B 中的数字
【发布时间】:2015-01-02 01:48:32
【问题描述】:

我正在用python解决一个问题。

我有 2 个带数字的字符串,我需要找出字符串 B 中的数字是否位于字符串 A 中。

例如:

a = "5, 7" 
b = "6,5"

A 和 B 可以包含任何数字和数量。

如果字符串 B 的数量在 A 中,我希望结果为真或假。

很遗憾,我不知道该怎么做。

【问题讨论】:

  • 数字是整数吗?

标签: python arrays string python-3.x compare


【解决方案1】:

你有字符串,而不是整数,所以你必须先将它们转换为整数:

a_nums = [int(n) for n in a.split(',')]
b_nums = [int(n) for n in b.split(',')]

这使用list comprehensionstr.split() method 调用的每个结果转换为带有int() function 的整数。

要测试两个序列中是否有数字,您可以使用sets,然后测试是否有交集:

set(a_nums) & set(b_nums)

如果结果不为空,则序列之间存在共享数字。由于非空集 are considered 'true',在 Python 中,您可以使用 bool() 将其转换为布尔值:

bool(set(a_nums) & set(b_nums))

集合是迄今为止测试此类交叉点最有效的方法。

使用生成器表达式和set.intersection() method

bool(set(int(n) for n in a.split(',')).intersection(int(n) for n in b.split(',')))

或者使用map() 函数可能更紧凑:

bool(set(map(int, a.split(','))).intersection(map(int, b.split(','))))

演示:

>>> a = "5, 7" 
>>> b = "6,5"
>>> bool(set(map(int, a.split(','))).intersection(map(int, b.split(','))))
True

或将其分解一下:

>>> [int(n) for n in a.split(',')]
[5, 7]
>>> [int(n) for n in b.split(',')]
[6, 5]
>>> set(map(int, a.split(',')))
set([5, 7])
>>> set(map(int, a.split(','))).intersection(map(int, b.split(',')))
set([5])
>>> bool(set(map(int, a.split(','))).intersection(map(int, b.split(','))))
True

【讨论】:

    【解决方案2】:

    如果数字是整数,获取True/False条目列表对应b中的每个数字是否在a中,尝试:

    a = "5, 7" 
    b = "6,5"
    A = [int(x) for x in a.split(',')]
    B = [int(x) for x in b.split(',')]
    c = [x in A for x in B]
    print(c)
    

    输出:

    [False, True]
    

    要找出b 中的任何个数字是否在a 中,然后:

    any(c)
    

    输出:

    True
    

    【讨论】:

    • 我只想要 1 个结果 = 我不将 6 与 5 和 5 与 7 进行比较,而是将 6 与 5 和 7 进行比较
    • 这个解决方案是这样做的:例如,如果b="7,5",它将返回[True, True]
    【解决方案3】:
    #This should do the trick
    a_ints = [int(i) for i in a.split(',')]
    b_ints = [int(i) for i in b.split(',')]
    for item in b_ints:
        for items in a_ints:
            if item==items: return true
    return false
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      相关资源
      最近更新 更多