【问题标题】:Duplicate Name in Query String查询字符串中的重复名称
【发布时间】:2021-10-13 10:05:24
【问题描述】:

如何用python输入一行查询字符串(不知道有多少字段,也不知道字段名有没有重复),输出没有重复字段的查询字符串(顺序字段不变)? 示例:

输入:username=peter&score=80&username=john

输出:username=john&score=80

【问题讨论】:

  • 您能添加到目前为止您尝试编写的代码吗?另外,如果您将此称为“查询字符串”,是否意味着它是 Web 应用程序的一部分?如果是这样,您使用什么框架?

标签: python python-3.x dictionary


【解决方案1】:

一个简单的解决方案就像

query = "username=peter&score=80&username=john"
unique = {f[0]:f[1] for f in [field.split("=") for field in query.split("&")}]}
output= "&".join([f"{field}={value}" for field, value in unique.items()])

但是,准确地说,这是一个快乐的路径解决方案。如果输入格式有问题,这将失败。使用适当的库来处理查询字符串是理想的选择。字段的唯一性由这里的键单独确定。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-16
    • 2011-03-11
    • 2011-04-16
    • 2013-08-03
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多