【问题标题】:How do I compare inputs[0] and inputs[1] to see if they are similar?如何比较输入[0] 和输入[1] 以查看它们是否相似?
【发布时间】:2017-04-08 12:11:30
【问题描述】:

我正在制作这个小 Python 项目,如果您输入了要输入的迭代次数(两组)并检查每对是否相似。

inputs = []
iterations = int(input())
loop_counter = 0
printNum = 0

while loop_counter<iterations*2:
    currentInput = input()
    inputs.append(currentInput)
    loop_counter += 1
    print(inputs[printNum])
    printNum+=1

所以,我想要这样的东西:

if(inputs[0] similar inputs[1]): #code here

【问题讨论】:

  • 只有单词会被移动还是什么?我的意思是,在您在 Aditi 的答案中分享的示例中,只有单词被转移了。我说对了吗?
  • “相似”是什么意思?请在您的问题正文中进行解释。

标签: python arrays list arraylist project


【解决方案1】:

如果你想检查它们是否相等
您只需这样做:

if inputs[0]==inputs[1]:
    #your code  

对于相似商,您可以按照以下方式进行:

set1 = set(inputs[0].split(' '))
set2 = set(inputs[1].split(' '))
if set1 == set2:
    #your code

比较“ben bro”和“ben mate”

i1= inputs[0].split()
i2 = inputs[1].split()
for ii in i1:
    if ii in i2:
         print("test!")

【讨论】:

  • 问题在于它们两者必须相同。例如,如果 inputs[0] == "mt bra" 和 inputs[1] == "bra mt" 我希望这两者进行比较,它应该返回相似的结果。
  • 在这里,当您将字符串拆分为列表并将它们转换为字符串时,您将收到TypeError: unhashable type: 'list' 错误!
  • 为什么一定要转回字符串?输入[0] 和输入[1] 具有原始字符串
  • Aditi,我的代码有问题。我现在的代码:inputs = [] iterations = int(input()) loop_counter = 0 printNum = 0 def check(): set1 = set(inputs[0].split(' ')) set2 = set(inputs[1].split(' ')) if set1 == set2: print("test!") while loop_counter&lt;iterations*2: currentInput = input() inputs.append(currentInput) loop_counter += 1 print(inputs[printNum]) printNum+=1 check() def check2(): if (loop_counter&gt;=iterations*2): check()
  • 它说'1'在列表中太远了。或者类似的东西。
【解决方案2】:

您基本上可以对拆分后的字符串进行排序(按空格拆分 - 默认行为)然后比较它们!

sorted(input[0].split())==sorted(input[1].split())

例子,

>>> input=['know it','it know']
>>> sorted(input[0].split())==sorted(input[1].split())
True

编码愉快!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多