【问题标题】:List Elements manipulation列表元素操作
【发布时间】:2017-07-25 17:04:19
【问题描述】:

假设我有一个列表,

['1-2', '1-3', '2-1', '3-2', '3-3', '6-1', '5-1', '4-1', '8-3', '8-2', '7-1', '9-1']

我需要输出唯一的元素,假设如果有 1-2 和 1-3,我只需要输出实例中的 1 个,并且这些应该是没有 - 的排序顺序。

样本输出:

1 2 
2 1
3 2
4 1
5 1
6 1
7 1
8 2
9 1

【问题讨论】:

  • ['1 2','2 1', '3 2', '4 1', '5 1', '6 1', '7 1','8 2', ' 9 1'] 在结果列表中
  • 您似乎希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的程序员编写代码,但他们通常只在发布者已经尝试自己解决问题时才提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出和您实际获得的输出(输出、回溯等)。您提供的详细信息越多,您可能收到的答案就越多。检查FAQHow to Ask
  • answerlist = [] 对于 anslist 中的项目: answerset = set(anslist) print answerset answerlist = list(answerset) answerlist.sort() print "Sorting", answerlist
  • 在上面的代码中,我尝试将其转换为 set 并返回到 list 并对其进行排序,但它只是对其进行了排序,但没有删除重复项

标签: python string python-2.7 list


【解决方案1】:
l = ['1-2', '1-3', '2-1', '3-2', '3-3', '6-1', '5-1', '4-1', '8-3', '8-2', '7-1', '9-1']
l.sort()
added = []
for line in l:
    itms = line.split("-")
    if itms[0] in added:
        continue
    added.append(itms[0])
    print("%s %s" % (itms[0], itms[1]))

【讨论】:

    猜你喜欢
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 2019-01-05
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多