为名称对分配相同的ID

时间:2014-06-29 05:12:56

标签: python list

nameList = ["sam", "tom", "jack", "james" , "robbie", "Lewis"]
id = 1

有一个nameList和一个id初始化为1.

我想为列表中的前两个名称指定名称id,然后递增id。

到目前为止我的代码段:

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

所需的输出是: -

sam,1
tom,1
jack,2
james,2
robbie,3
Lewis,3

有任何帮助吗?感谢

5 个答案:

答案 0 :(得分:3)

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

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

注意每次迭代i上的数字将采用[0, length-1]

范围内的数字

答案 1 :(得分:3)

您可以使用enumerate简单地迭代列表并使用(index / 2) + 1,您可以获得要打印的实际值

nameList = ["sam", "tom", "jack", "james", "robbie", "Lewis"]
for idx, item in enumerate(nameList):
    print "{}, {}".format(item, (idx / 2) + 1)

<强>输出

sam, 1
tom, 1
jack, 2
james, 2
robbie, 3
Lewis, 3

答案 2 :(得分:0)

for names in nameList:
    print names + "," + str((id+1)/2)
    id = id + 1

答案 3 :(得分:0)

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))

我更喜欢这种方式,因为如果你想在x而不是2次迭代后递增它,你可以将它改为counter(1, x)

答案 4 :(得分:0)

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