lundi 5 décembre 2016

I need help! Read from CSV for matching condition or less than value using Python

I have a problem where:

Within a social network:

  • Any user may post original content
  • Any user may repost original content or another user's repost
  • Any user may follow any other user

The social network data is represented in a CSV file with the following format:

postId, repostId, followers
1, -1, 120
2, 1, 60
3, 1, 30
4, 2, 90
5, 3, 40
6, 4, 10
7, -1, 240
8, 7, 190
9, 7, 50

Where:

  • postId - The ID of the post or repost
  • repostId - The ID of the content that was reposted or -1 if this is an original post
  • followers - The number of followers the user that made the post has

My motivation is to read from a cell while the CSV file is open, then if the cell is less than zero, then I know it is a unique post. However this leaves part of the summation incomplete, so I was looking at if a specified value within the row matches the condition.

My solution:

# import csv module
import csv

# ensure path to csv file is apporpriate in temp
with open("filepath", 'rb') as f:
    reader = csv.DictReader(f)
    rows = [row for row in reader if row['repostId'] <= '0'] # go through each row of repostId, looking for a negative value

# for each iteration of rows, print the number of corresponding followers
for followers in rows:
    print followers

Aucun commentaire:

Enregistrer un commentaire