Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copying strings to the list in Python

I have a list data, and I am reading lines from it.

item = user = channel = time = []
with open('train_likes.csv') as f:
    data = csv.reader(f)
    readlines = f.readlines()

I want to split each line into single string elements and append each element to a one of 2 other lists: user, items

    for line in readlines:
        Type = line.split(",")
        Copy1 = Type[0]
        Copy2 = Type[1]
        user.append(Copy1)
        item.append(Copy2)

But when appending item, user is appended with Copy2 as well, and item got the same as user!!!

user's and item's value's

I have checked all familiar replies, but that didn't help me (I tried to copy everything in the script, here's only one version.


2 Answers

When you write item=user=channel=time=[], you are creating only one object, with 4 aliases. So appending to item is the same as appending to user. Instead you should write

item, user, channel, time = [], [], [], []

or simply

item = []
user = []
channel = []
time = []
like image 56
Greg Avatar answered Mar 11 '26 11:03

Greg


As @Greg points out, you are creating one list object and assigning it to four variables.

You don't appear to use channel or time in your code, however. In addition, this is a more memory efficient way to read your file. You are reading each line separately instead of the whole file at once.

item = []
user = []
with open('train_likes.csv') as f:
    reader = csv.reader(f)
    for line in reader:
        # Splits on whitespace taking at most three splits (with zero indexing, 2 equals 3...).
        u, i, _ = ", ".join(line).split(", ", 2)  
        item.append(i.strip())
        user.append(u.strip())
like image 33
Alexander Avatar answered Mar 11 '26 11:03

Alexander