按索引从列表中选择,但保留lis中的其他关联项

2024-06-28 20:17:57 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有一个像这样的二维列表。。。在

myList=[['ab','0_3','-1','1'],['bm','2_1','-3','2'],['am','4_1','-1','3'],...]]

例如,'-1','1'是x,y坐标(最后2列),我希望只显示列表的一部分,其索引如下。。。在

^{pr2}$

…因此用户可以通过索引号选择其中一个作为原点。我想我可以列举。。。在

for row in enumerate(myList):
     i, a= row
     col= (i, a[0])
     newList.append(col)
     print cols

但是,一旦我要求用户选择一个ie.user选择了'0'并设置了变量origin='ab',那么如何获得与origin关联的x、y(或[2]、[3])列作为原点坐标(我需要能够与列表的其余部分进行比较)?在

使用这个方法,我可以用某种方式使用分配给所选点的变量,即origin = ab,然后得到它的x,y并将它们赋给x1,y1。。。 因为enumerate给出了2个元组(i,a)并将它们附加到newList中,这就是我在newList中所拥有的全部,还是可以附加其他列而不显示它们? 我希望我的解释足够清楚。。。我只有残破的密码自动取款机


所以我终于有了大部分的工作。。。在

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,这很好,但它总是提示我输入一个数字。有什么建议吗?在


Tags: csv用户in列表foraboriginrow
1条回答
网友
1楼 · 发布于 2024-06-28 20:17:57

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

样本输出:

^{pr2}$

相关问题 更多 >