简体   繁体   中英

How to find sequence number of list in python (like line number 1, 2)

I want to find out the line number of the list,

def creatList(file):
    try:
        for line in file:
            line=(line.rstrip()).split()
            rawList=[]
            rawList.append(line)
            creatRuleFile(rawList)

    finally:
        print("line(s) printed")

    def creatRuleFile(new):
        print(new)

inside creatRuleFile(rawList) function Im tring to display something similarly like this,

1. [a,b,c] 
2. [f,h,k] 
3. [b,s,y]

You can use a global variable (bad practice) for the counter, but a better method would be:

def creatList(file):
    try:
        for i, line in enumerate(file):
            ...
            creatRuleFile(i, rawList)
    ...

and

def creatRuleFile(i, new):
    print("{0}. {1}".format(i, new))

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