简体   繁体   中英

Python remove duplicates from array

i've got an array wich contains an entire column from my csv file wich has alot of duplicates since the csv consist of users their contact info and their current group.

So the users in the CSV are in a group but sometime mulitple users are in the same group now the point of this python script is too sort all the users that are in the same group in a row like. i'll update the main thread so it wont confuse more ppl sorry.

The end goal is of this script will be to put the group in a row together with the phone numbers of the users that are in that group like this.

GroupName, PhoneNumber1, PhoneNumber2, PhoneNumber3, PhoneNumber4, etc

Example:

Name,  email, phonenumber, **group**
name1, name2, number1,     ExampleGroup

So i've tried sorting it by using this: https://wiki.python.org/moin/HowTo/Sorting

And it returns:

['a', ' ', 'E', 'g', 'i', 's', 'm', 'M', 'L', 'o', 'l', 'p', 'S', 'R', 't', 'h', 'e', 'n']

The code i'm using at the moment:

import csv
    with open('Configtool.csv', 'rb') as f:
        reader = csv.reader(f, delimiter=';', quoting=csv.QUOTE_NONE)
        for row in reader:
         groupname = row[5]
         #print groupname
         sortedgroup = list(set(groupname))
         print sortedgroup

Your help is much appreciated,

Note that i'm new to python so please go easy on me :p

You can use itertools.groupby to get all the rows with the same group and then use a dictionary comprehension to create a dictionary mapping the groups to phone numbers.

import itertools
groups = itertools.groupby(reader, key=lambda row: row[3])
d = {group: [row[2] for row in rows] for (group, rows) in groups}

(Assuming that the group in in position 3 and the phone number in position 2 of the rows. Also you might have to remove your loop, otherwise the reader iterator will already be exhausted.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM