如果我有2d这样的积分......
myList=[['ab','0_3','-1','1'],['bm','2_1','-3','2'],['am','4_1','-1','3'],...]]
其中'-1','1'
例如是x,y坐标(最后2列),我希望只显示列表的一部分,其索引像这样......
[0] ab # I don't want to display the other list items, just the index and first col
[1] bm
[2] am
...因此用户可以通过索引号选择其中一个来创建原点。我想我可以这样列举......
for row in enumerate(myList):
i, a= row
col= (i, a[0])
newList.append(col)
print cols
但是一旦我要求用户选择一个即。用户选择'0'并设置变量origin='ab'
,如何获取与原点相关的x,y(或[2],[3])列作为原点坐标(我需要能够与列表的其余部分进行比较)?
使用此方法,我可以以某种方式使用分配给所选点的变量,即。 origin = ab
,然后得到它的x,y并将它们分配给x1,y1 ......
因为enumerate给出了2个元组(i,a)并将它们附加到newList
,所以我在newList
中只有它,或者我是否还可以追加其他列但不显示它们?
我希望我的解释足够清楚......我只有严重的代码atm
所以我终于完成了大部分工作......
import csv
myList=[]
try:
csvr = open('testfile.csv','r')
next(csvr, None)
theList = csv.reader(csvr)
for row in theList:
myList.append(row)
for row in enumerate(myList):
i, a = row
print i, a[0]
except IOError:
print 'Error!!!'
try:
choice = raw_input("Select a set: ") # Can also enter 'e'
if choice=='e'
print 'exiting'
else:
pass
user_choice = myList[int(choice)]
name, id, x, y= user_choice
print name, id,
return float(x), float(y)
except:
print 'error'
它按预期打印,我现在可以返回x,y,这很棒,但它只是一直提示我输入一个数字。有什么建议吗?
答案 0 :(得分:0)
1)保持列表格式,您可以使用用户的选择作为列表索引:
myList = [['ab','0_3','-1','1'],['bm','2_1','-3','2'],['am','4_1','-1','3']]
for row in enumerate(myList):
i, a = row
print i, a[0]
choice = int(raw_input("Select a set: "))
user_choice = myList[choice]
name, id, x, y = user_choice
print name, id, float(x) + float(y) # use float() to convert strings to floats
示例输出:
~ $ python tester.py
0 ab
1 bm
2 am
Select a set: 1
bm 2_1 -1.0