Last active
February 11, 2018 19:21
-
-
Save tommeagher/5797589 to your computer and use it in GitHub Desktop.
Create an edge list in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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
Or just use itertools.combinations
http://docs.python.org/2/library/itertools.html#itertools.combinations