用python创建一个列表,分别打印出列表的索引号和索引号对应的值

Python010

用python创建一个列表,分别打印出列表的索引号和索引号对应的值,第1张

list1 = ['a','b','c']

fmt = 'index %d value is %s'

print ', '.join([fmt % (idx, val)

    for idx, val in enumerate(list1)

    ])

# or

print ', '.join(map(

    lambda x: fmt%x, 

    enumerate(list1)

    ))

如下:

1、index函数:用于从列表中找出某个值第一个匹配项的索引位置。

2、index方法语法:list.index(x[, start[, end]])。

3、参数:x-- 查找的对象。start-- 可选,查找的起始位置。end-- 可选,查找的结束位置。

4、返回值:该方法返回查找对象的索引位置,如果没有找到对象则抛出异常。

5、实例:

代码:str1 = "this is string example....wow!!!";str2 = "exam"。

index函数为print(str1.index(str2))。

python中index函数怎么用?

Python中index方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find方法一样,只不过如果str不在string中会报一个异常。

index函数一般用处是在序列中检索参数并返回第一次出现的索引,没找到就会报错。

s = raw_input()

lines = s.split('\n')

dictlines = lines[:100]

mydict = {}

# read 

for i,line in enumerate(dictlines ):

    for word in line.split():

      mydict.setdefault(word,[]).append(i + 1)

# print indices

for word in mydict.keys():

    print "%s: %s"  % (word,", ".join(map(str,sorted(mydict[word]))))

 

def andSearch(words_list):

    global mydict

    a = set(range(1,101))

    for word in words_list:

        a = a.intersection(set(mydict[word])) 

     return a 

def orSearch(words_list):

    global mydict

    a = set([])

    for word in words_list:

        a = a.union(set(mydict[word]))

    return a 

    

# Query

index = 100

u = lines[index]

while index < len(lines):

    words_list = u.split()

    if ":" in u:

        if words_list[0] == "OR:":

            a = orSearch(words_list)

        else:

            if words_list[0] == 'AND:':

               words_list = words_list[1:]

            a = andSearch(words_list)

    if not a:

        print ", ".join(map(str,list(a)))

    else:

        print "None"

    index += 1

大致思想就是这样。。。。。。。。