Python 为成对的名称分配相同的ID

Python 为成对的名称分配相同的ID,python,list,Python,List,有一个姓名列表和一个初始化为1的id 我想为列表中的前两个名称分配名称id,然后增加id 到目前为止,我的代码片段: nameList = ["sam", "tom", "jack", "james" , "robbie", "Lewis"] id = 1 所需输出为:- nameList = ["sam", "tom", "jack", "james" , "robbie", "Lewis"] id = 1 for names in nameList: print names + "

有一个姓名列表和一个初始化为1的id

我想为列表中的前两个名称分配名称id,然后增加id

到目前为止,我的代码片段:

nameList = ["sam", "tom", "jack", "james" , "robbie", "Lewis"]
id = 1
所需输出为:-

nameList = ["sam", "tom", "jack", "james" , "robbie", "Lewis"]
id = 1
for names in nameList:
    print names + "," + str(id)
    id = id + 1
有什么帮助吗?谢谢

您可以尝试使用并检查字符串的索引是否为偶数。如果是,则增加
id

sam,1
tom,1
jack,2
james,2
robbie,3
Lewis,3
for names in nameList:
    print names + "," + str((id+1)/2)
    id = id + 1

注意在每次迭代中,
i
将取范围
[0,length-1]
的数字,您只需使用
枚举
迭代列表,然后使用
(index/2)+1
,即可获得要打印的实际值

nameList = ["sam", "tom", "jack", "james" , "robbie", "Lewis"]
id = 0
for i, names in enumerate(nameList):
    if i % 2 == 0:   # if 'i' is even
        id = id + 1   # or id += 1, both are equivalent
    print names + "," + str(id) # if all elements are strings, 'str()' is not required
输出

sam,1
汤姆,1岁
杰克,2岁
詹姆斯,2岁
robbie,3岁
刘易斯,3岁
我更喜欢这种方式,因为如果您想在x之后而不是在2次迭代之后增加它,您可以将其更改为
计数器(1,x)

id=1
c=0
对于名称列表中的名称:

如果cI喜欢这个答案,那么它比被接受的答案更好。不冒犯被接受的人,但这更简单1回答得很好,只是想指出不一致性:
(索引+2)/1
的加号和除法颠倒了。
nameList = ["sam", "tom", "jack", "james", "robbie", "Lewis"]
for idx, item in enumerate(nameList):
    print "{}, {}".format(item, (idx / 2) + 1)
nameList = ["sam", "tom", "jack", "james" , "robbie", "Lewis"]

def counter(start, duplicate_amt=1):
    while True:
        for _ in range(duplicate_amt):
            yield start
        start += 1

for name, _id in zip(nameList, counter(1, 2)):
    print("{},{}".format(name, _id))
id=1
c=0
for name in nameList:
    if c<=2:
        c+=1
    else:
        id+=1
        c=1
    print "{}, {}".format(name,id)