在Python中通过字典或列表进行FOR循环时,如何获取项的键?--python基础

1. 在Python中通过字典或列表进行FOR循环时,如何获取项的键?

对于lists和dicts ,答案是不同的.

A list没有key.每个项目都有一个索引.您可以枚举这样的列表:

>>> l = ['A','B','C','D']
>>> for index, item in enumerate(l):
...     print index
...     print item
... 
0
A
1
B
2
C
3
D

我在这里使用了你的例子,但是调用list' l',以避免与保留字冲突.

如果你遍历a dict,你就会获得密钥:

>>> d = {0: 'apple', 1: 'banana', 2: 'cherry', 3: 'damson', }
>>> for k in d:
...     print k
...     print d[k]
... 
0
apple
1
banana
2
cherry
3
damson

你想要索引,而不是密钥.为此,您可以使用枚举:

for index, item in enumerate(l):
    print index
    print item

这在Python教程中的循环技术一节中提到,该教程还介绍了在获取键和值时循环字典.

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
...     print k, v
...
gallahad the pure
robin the brave

 2.django中批量插入数据 

django的orm自带了一个bulk_create方法,大大缩减了我们插入数据的时间!

def book(request):
    book_list=[] #先定义一个空列表
    # 再生成10000个对象,此时并没有操作数据库
    for info in range(10000):
        book_obj=models.Book(price='%s'%info)
        # 把对象添加到列表里
        book_list.append(book_obj)
    models.Book.objects.bulk_create(book_list)  #调用了orm的bulk_create方法
    # 展示到前端页面
    book_queryset = models.Book.objects.all()
    return render(request,'book.html',locals())

转载:https://www.cnblogs.com/suncolor/p/16584631.html

自己项目:

def select_obj(request):

    # 批量插入
    id = request.POST.get('id')
    ids = request.POST.get('ids')## 这里获取是json数组
    obj_list = []
    ids_new = json.loads(ids) ##json数组
    for index, item in enumerate(ids_new):
        print(item)
        obj = StudentOrderList(
            coerse_id=item,
            student_order_id=id
        )
        obj_list.append(obj)
    StudentOrderList.objects.bulk_create(obj_list)

    return JsonResponse({'status': 200, 'msg': '保存成功'})

 

 3.Python两个列表合并为一个字典

list1 = ['name','age','gender']
list2 = ['chris','21','girl']

dict1 = {list1[i]:list2[i] for i in range(len(list1))}
print(dict1)

 

 

posted @ 2022-11-08 15:15  搬砖小伙子  阅读(354)  评论(0)    收藏  举报