Skip to content

Instantly share code, notes, and snippets.

@tommeagher
Last active February 11, 2018 19:21
Show Gist options
  • Save tommeagher/5797589 to your computer and use it in GitHub Desktop.
Save tommeagher/5797589 to your computer and use it in GitHub Desktop.
Create an edge list in Python.
mylist = ['john', 'paul', 'george', 'ringo', 'matthew', 'mark', 'luke']
resultlist = []
for person in mylist:
myindex = mylist.index(person)
newlist = mylist[:myindex]+mylist[myindex+1:] #make a new temp list without the person in it
for item in newlist:
mytuple = (person, item)
backtuple = (item, person)
if backtuple not in resultlist: #remove any reversed duplicates
resultlist.append(mytuple)
@tommeagher
Copy link
Author

@tommeagher
Copy link
Author

To do multiple rows in a CSV:

import csv

csvfile = open("groups.csv", "r")
reader = csv.reader(csvfile)

resultlist = []

outfile=open("edgelist.csv", "w")
writer=csv.writer(outfile)
for row in reader:
    for person in row:
        myindex = row.index(person)
        newlist = row[:myindex]+row[myindex+1:]   #make a new temp list without the person in it
        for item in newlist:
            mytuple = (person, item)
            backtuple = (item, person)
            if backtuple not in resultlist: #remove any reversed duplicates
                resultlist.append(mytuple)
                writer.writerow(mytuple)

csvfile.close()
outfile.close()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment