*args and **kwargs?

This question already has an answer here: What does ** (double star/asterisk) and * (star/asterisk) do for parameters? 15 answers The syntax is the * and ** . The names *args and **kwargs are only by convention but there's no hard requirement to use them. You would use *args when you're not sure how many arguments might be passed to your function, ie it allows you pass an arbitrar

*参数和** kwargs?

这个问题在这里已经有了答案: **(双星/星号)和*(星号/星号)对参数做什么? 15个答案 语法是*和** 。 名字*args和**kwargs只是惯例,但没有硬性要求使用它们。 当你不确定有多少参数可能传递给你的函数时,你会使用*args ,即它允许你传递任意数量的参数给你的函数。 例如: >>> def print_everything(*args): for count, thing in enumerate(args): ... print( '{0}. {1}'.format(count,

How do I sort a dictionary by value?

I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question How do I sort a list of dictionaries by values of the dictionary in Python? and probably could change my code to have a

如何按价值对字典进行排序?

我有一个从数据库中的两个字段中读取值的字典:一个字符串字段和一个数字字段。 字符串字段是唯一的,所以这是字典的关键。 我可以对键进行排序,但是如何根据这些值进行排序? 注意:我已阅读Stack Overflow问题如何按Python中字典的值对字典列表进行排序? 并可能可以改变我的代码有一个字典的列表,但因为我真的不需要一个字典的列表,我想知道是否有一个更简单的解决方案。 为了完整起见,我使用heapq发布了一个解决

sort dict by value python

Assume that I have a dict. data = {1:'b', 2:'a'} And I want to sort data by 'b' and 'a' so I get the result 'a','b' How do I do that? Any ideas? To get the values use sorted(data.values()) To get the matching keys, use a key function sorted(data, key=data.get) To get a list of tuples ordered by value sorted(data.items(), key=lambda x:x[1]) Related: see the discussion

按值python排序字​​典

假设我有一个字典。 data = {1:'b', 2:'a'} 我想按'b'和'a'排序数据,以便得到结果 'a','b' 我怎么做? 有任何想法吗? 获取值使用 sorted(data.values()) 要获得匹配的键,请使用key功能 sorted(data, key=data.get) 获取按值排序的元组列表 sorted(data.items(), key=lambda x:x[1]) 相关内容:请参阅此处的讨论:字典以Python 3.6+订购 如果你真的想对字典进行排序而不是仅仅获得一个排序列表

How to remove items from a list while iterating?

I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. for tup in somelist: if determine(tup): code_to_remove_tup What should I use in place of code_to_remove_tup ? I can't figure out how to remove the item in this fashion. You can use a list comprehension to create a new list containing only the elements you don

如何在迭代时从列表中删除项目?

我遍历Python中的元组列表,并试图在符合特定条件时将其删除。 for tup in somelist: if determine(tup): code_to_remove_tup 我应该用什么来代替code_to_remove_tup ? 我无法弄清楚如何以这种方式去除物品。 您可以使用列表理解来创建一个仅包含您不想删除的元素的新列表: somelist = [x for x in somelist if not determine(x)] 或者,通过分配片段somelist[:] ,可以对现有列表进行变异以仅包含所需的

Random string generation with upper case letters and digits in Python

I want to generate a string of size N. It should be made up of numbers and uppercase English letters such as: 6U1S75 4Z4UKK U911K4 How can I achieve this in a pythonic way? Answer in one line: ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) or even shorter starting with Python 3.6 using random.choices() : ''.join(random.choices(string.ascii_uppercas

在Python中随机生成大写字母和数字的字符串

我想要生成一个大小为N的字符串 它应该由数字和大写英文字母组成,例如: 6U1S75 4Z4UKK U911K4 我怎样才能以pythonic的方式实现这一点? 一行回答: ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) 或者使用random.choices()从Python 3.6开始更短: ''.join(random.choices(string.ascii_uppercase + string.digits, k=N)) 密码更安全的版本; 请参阅https://stackoverflo

Generate random integers between 0 and 9

How can I generate random integers between 0 and 9 (inclusive) in Python? ie 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 Try: from random import randint print(randint(0, 9)) More info: https://docs.python.org/3/library/random.html#random.randint import random print(random.randint(0,9)) random.randint(a, b) Return a random integer N such that a <= N <= b. Docs: https://docs.python.org/3.

生成0到9之间的随机整数

我如何在Python中生成0到9(含)之间的随机整数? 即0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 尝试: from random import randint print(randint(0, 9)) 更多信息:https://docs.python.org/3/library/random.html#random.randint import random print(random.randint(0,9)) random.randint(a, b) 返回一个随机整数N,使得a <= N <= b。 文档:https://docs.python.org/3.1/library/random.html#rando

How to remove a key from a python dictionary?

When trying to delete a key from a dictionary, I write: if 'key' in myDict: del myDict['key'] Is there a one line way of doing this? Use dict.pop() : my_dict.pop('key', None) This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (ie. my_dict.pop('key') ) and key does not exist, a KeyError is raised. Specifi

如何从Python字典中删除密钥?

当试图从字典中删除密钥时,我写道: if 'key' in myDict: del myDict['key'] 有没有一种方法可以做到这一点? 使用dict.pop() : my_dict.pop('key', None) 如果key存在于字典中,这将返回my_dict[key] ,否则返回None 。 如果未指定所述第二参数(即my_dict.pop('key')和key不存在,一个KeyError上升。 具体回答“是否有一条这样做的路线?” if 'key' in myDict: del myDict['key'] ...好吧,你问了;-)

Map two lists into a dictionary in Python

Imagine that you have: keys = ('name', 'age', 'food') values = ('Monty', 42, 'spam') What is the simplest way to produce the following dictionary ? a_dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'} This code works, but I'm not really proud of it : a_dict = {} junk = map(lambda k, v: a_dict.update({k: v}), keys, values) Like this: >>> keys = ['a', 'b', 'c'] >>>

将两个列表映射到Python中的字典中

想象一下,你有: keys = ('name', 'age', 'food') values = ('Monty', 42, 'spam') 生成下列字典最简单的方法是什么? a_dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'} 此代码有效,但我并不为此感到自豪: a_dict = {} junk = map(lambda k, v: a_dict.update({k: v}), keys, values) 喜欢这个: >>> keys = ['a', 'b', 'c'] >>> values = [1, 2, 3] >>> dictionary = dict(zip(k

Add new keys to a dictionary?

Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an .add() method. >>> d = {'key':'value'} >>> print(d) {'key': 'value'} >>> d['mynewkey'] = 'mynewvalue' >>> print(d) {'mynewkey': 'mynewvalue', 'key': 'value'} >>> x = {1:2} >>> print x {1: 2} >>> x.update({3:4}) >>>

将新密钥添加到字典中?

是否可以在创建Python字典后添加一个键? 它似乎没有.add()方法。 >>> d = {'key':'value'} >>> print(d) {'key': 'value'} >>> d['mynewkey'] = 'mynewvalue' >>> print(d) {'mynewkey': 'mynewvalue', 'key': 'value'} >>> x = {1:2} >>> print x {1: 2} >>> x.update({3:4}) >>> print x {1: 2, 3: 4} 我觉得整理有关Python字典的信息: 创建

How are Python's Built In Dictionaries Implemented

Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer. Here is everything about Python dicts that I was able to put together (probably more than anyone would like to know; but the answer is comprehensive). Python dictionaries are implemented as hash

Python的内置字典是如何实现的

有谁知道python的内置字典类型是如何实现的? 我的理解是它是某种散列表,但我一直没能找到任何明确的答案。 以下是我能够放在一起的所有Python字典(可能比任何人都想知道的更多;但答案是全面的)。 Python字典被实现为散列表 。 散列表必须允许散列冲突,即使两个不同的键具有相同的散列值,表的实现也必须具有明确插入和检索键和值对的策略。 Python dict使用开放寻址来解决散列冲突(如下所述)(请参阅dictobject.