简体   繁体   中英

How to assign Python list element? SyntaxError: cannot assign to function call

I read my file into list.

with open ('myf','r') as f:
    lines = f.read().splitlines()

I can make my class instances, one by one.

p0 = Payload(lines[0])
p1 = PayLoad(lines[1])

My ideas is to automate this

p =str('p6_')
>>> for i in lines:
...     Payload(lines[i]) = p + str(i)
... 
  File "<stdin>", line 2
SyntaxError: cannot assign to function call

How to solve this assign problem?

You want to build a list, like this:

p = [*map(Payload, lines)]

then you can access by index, like this:

p[0],
p[6],
p[whatever_number_you_need]

I think you want to assign the new Payload objects to variables named pX , where X is the line number. If that is the case:

for x in range(len(lines)):
    globals()['p%i' % x] = Payload(lines[x])

would do it, as globals() returns a dictionary where the key is the variable name and the value is the value of the variable. If I didn't understand it correctly, please tell me. Hope I can help you!

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