试图找出列表中的位置

时间:2012-02-29 02:07:35

标签: python list

例如,我正在寻找一种方法来搜索列表中的每个点,以查看对象的位置。一些示例的伪代码可以去:

for every column in current row:
  if column is the first one:
                  do this
  if column in the last one:
                  do that
  else:
     find the previous row and columns place

基本上我处于停滞状态,所以任何见解都会有所帮助,谢谢

编辑示例代码:

for row in range(0,h+1):
      newrow=[]
      if row==0:
           newrow=[1]
      elif row==1:
           newrow=[1,1]
      else:
          for column,x in enumerate(row):
              if column==0:
                  newrow.append(1)
              elif column==len(row)-1:
                  newrow.append(1)
              else:
                  newrow.append(2)

2 个答案:

答案 0 :(得分:1)

您在寻找list.index吗?

l = ['foo', 'bar', 'baz']
i = l.index('bar')
# i is 1, because l[1] == 'bar'

如果您需要根据它是第一个还是最后一个项目进行特殊处理:

# using i from above
if i == 0:
    # it's the first item
elif i == len(l) - 1:
    # it's the last item
else:
    # it's neither first nor last

或者如果您仍然需要处理所有项目,请考虑使用enumerate来跟踪整个循环中的索引:

for i, x in enumerate(mylist):
    if i == 0:
        # x is the first item
    elif i == len(mylist)-1:
        # x is the last item
    else:
        # x is in the middle

答案 1 :(得分:1)

bardockyo:

问题似乎是你的行中没有列表...当你为范围内的行(0,h + 1)运行代码时:',row将始终是一个带值的整数大于或等于0,小于或等于h。

您是否尝试一次读取一行文件,并跟踪行号?如果是这样,您应该使用单独的计数器来跟踪行号...

我不能完全遵循你想要完成的任务,所以我甚至无法生成代码来帮助你......

添加以回应bardockyo的评论:

我相信这可以实现你的目标:

# Setting h to a value so that I can use your 'range' line.
h = 5

# Create a blank dictionary object to store the row data.
rows = {}

for row_number in range(0,h+1):
    row_data = []
    # range isn't inclusive of the end value by default, to 'make it work', we
    # must add 1 to the row_number.
    for val in range(0,row_number+1):
        if val == 0 or val == row_number:
            # Determine if the value in 'val' is either the first number or
            # last number in this row, and if so append '1' to the list.
            row_data.append(1)
        else:
            # Determine if the value in 'val' is not the first number or last
            # number in this row, and if so append '2' to the list.
            row_data.append(2)
    # Store the row data in the row dictionary, with the key of 'row_number'.
    rows[row_number] = row_data

# Iterate through the dictionary.  There's no guarantee as to the order
# returned by the 'keys()' function, so I use sorted() to ensure it's in
# numerical order.
for row_num in sorted(rows.keys()):
    print 'Row Number %d contains the list:' % row_num,
    for val in rows[row_num]:
        print '%d' % val,
    print ''

# There are better (read: cleaner) ways to format the output for printing,
# but they can be hard to read.