【问题标题】:Check String equality where order is not important检查顺序不重要的字符串相等性
【发布时间】:2014-01-31 12:55:05
【问题描述】:

我有以下代码:

#Write the lines back which do NOT match the command
for line in lines:
    if line != command:
        file_writer.write(line)

我有两个示例 字符串

lines = [
    """user_operations.add_user("url",531,{u'Username': u'TEST123567', u'Status': u'Enabled', u'AccessTypes': [u'APN'], u'Auth': u'ServicePassword', u'ID': 7400, u'PasswordInfo': None, u'SSOInfo': None, u'Email': u'', u'AccountID': 531},False,headers)""",
    """user_operations.add_user("url",531,{u'Username': u'TEST123567', u'Status': u'Enabled', u'Email': u'', u'PasswordInfo': None, u'AccessTypes': [u'APN'], u'AccountID': 531, u'ID': 7400, u'Auth': u'ServicePassword', u'SSOInfo': None},False,headers)"""
]

是否有任何快速的“n”脏函数来检查它们是否包含相同的数据而不管顺序如何?

谢谢!

【问题讨论】:

  • 示例行似乎是 python 命令。你是把lines中的数据作为字符串还是python命令获取?
  • 您的问题需要澄清。例如——我不知道这是否是最好的问题——输入行是否总是以user_operations.add_user 开头,在这种情况下,真正的问题是括号内的数据是否相同?还是输入行有多种不同的形式?
  • 这两行是字符串(它们实际上是python命令,但这无关紧要。),我需要一些与我发布的代码执行相同但会匹配子顺序的字符串-strings 无关紧要。
  • 如果你能得到数据,你可以使用ast.literal_eval从数据中制作一个真正的python dict,然后比较它们。
  • 对投票者有任何评论吗?

标签: python string string-comparison


【解决方案1】:

假设您在lines 中获得了一个字符串列表,下面的代码应该可以工作:

#Write the lines back which do NOT match the command
sorted_command = sorted(command)
for line in lines:
    if sorted(line) != sorted_command:
        file_writer.write(line)

【讨论】:

  • 你将如何获得一个字符串列表,你能告诉我吗?如果可以,这将不起作用,请给我看完整的 sn-p。
  • 你没有引用字符串,比如在 python 中不起作用的标题。你将如何处理它。
  • 输入应该是正确引用的字符串。我认为这个问题并不清楚。
  • 如果来自java脚本,可以不加引号。
猜你喜欢
  • 2019-08-29
  • 2020-02-23
  • 1970-01-01
  • 2011-10-29
  • 1970-01-01
  • 1970-01-01
  • 2012-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多