Code Academy 习题 列表元素去重

习题

Write a function remove_duplicates that takes in a list and removes elements of the list that are the same.

For example: remove_duplicates([1, 1, 2, 2]) should return [1, 2].

  • Don't remove every occurrence, since you need to keep a single occurrence of a number.
  • The order in which you present your output does not matter. So returning [1, 2, 3] is the same as returning [3, 1, 2].

自己解:

def remove_duplicates(raw_list):
  d = {}
  new_raw_list = []
  for item in raw_list:
    s_count = 0
    for i in range(len(raw_list)):
      if raw_list[i] == item:
        s_count += 1
        if s_count >=1:
          d[item] = s_count
  new_raw_list = d.keys()
  return new_raw_list

看了提示的解:

def remove_duplicates1(raw_list):
  new_raw_list = []
  for item in raw_list:
    if item not in new_raw_list:
      new_raw_list.append(item)
  return new_raw_list

总结:

... ...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值