简体   繁体   中英

python select item from list

I have the following in a .txt file which are saved from a game. i need to rerun the game inserting the items where appropriate.

(' A', '1', '2', '+1.25', '+0', '4', (123,321))
(' B', '1', '2', '-0', '+0.25', 'V', (05,245))
(' 1', '0', '6', '+0', '-0.25', 'V', (10,250))
(' 2', '0', '6', '-0.5', '-1.75', '4', (190,8))
(' 3', '2', '4', '-1', '1', '3', (180,100))

the code used to recover the items is:-

Z=[None]*10
i=0
TT = 'TestZZ.txt'
with open (TT, 'r') as f:
    array=[]
    for line in f:
        Z[i] = line
        i = i+1

the recovered list for Z[1] is "(' B', '1', '2', '-0', '+0.25', 'V', (05,245))\\n"

i need to get each item either as a string of num if I do Z[1][3] i get 'B' not -0 as expected

help please

A simpler and effective soluton could be

// Say Z[1] is "(' B', '1', '2', '-0', '+0.25', 'V', (05,245))\n"
import ast
print ast.literal_eval(Z[1]) 
// this should return (' B', '1', '2', '-0', '+0.25', 'V', (5, 245))

Hope this helps :)

The contents of Z[1] is string "(' B', '1', '2', '-0', '+0.25', 'V', (05,245))" , not a list as you may expect... And:

Z[1][0] = '('
Z[1][1] = "'"
Z[1][2] = ' '
Z[1][3] = 'B'

So the result is correct, simplified parser for your data would be:

>>> data = "(' B', '1', '2', '-0', '+0.25', 'V', (05,245))"
>>> data.split(',')
["(' B'", " '1'", " '2'", " '-0'", " '+0.25'", " 'V'", ' (05', '245))']
>>> data.split(',')[2]
" '2'"
>>> data.split(',')[2].strip(', ')
"'2'"
>>> data.split(',')[2].strip("' ")
'2'
>>>

But it doesn't handle strings like ' B, A' and so on... so you may want to write more robust parser. Alternatively you may use for example XML data format or use pickle .

I found a way using Pickle probably not the best but it seems to work.

import pickle
T=[None]*10
R=[None]*10
T[0]=('bs:','300:','test3.txt ','5:FR456')
T[1]=('Bisley', '400', '4', 'Fred', 'CD45')
T[2]=(' A', '1', '2', '+1.25', '+0', '4')
T[3]=(' B', '1', '2', '-0', '+0.25', 'V')
T[4]=(' 1', '0', '6', '+0', '-0.25', 'V')
T[5]=(' 2', '0', '6', '-0.5', '-1.75', '4')



output = open("save1.pkl", 'wb')
for i in range(0,10):


    pickle.dump(T[i], output)


output.close()

inputFile = open("save1.pkl", 'rb')

for i in range(0,10): R[i] = pickle.load(inputFile)

inputFile.close() for i in range(0,10): print R[i]

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