在Python中,我看到人们创建这样的字典:
d = dict( one = 1, two = 2, three = 3 )
Run Code Online (Sandbox Code Playgroud)
如果我的键是整数怎么办?当我尝试这个:
d = dict (1 = 1, 2 = 2, 3 = 3 )
Run Code Online (Sandbox Code Playgroud)
我收到一个错误.我当然可以这样做:
d = { 1:1, 2:2, 3:3 }
Run Code Online (Sandbox Code Playgroud)
哪个工作正常,但我的主要问题是:有没有办法使用dict()函数/构造函数设置整数键?
我有一个字母和字母簇列表,如下所示:
['x', 'str', 'a', 'pr']
Run Code Online (Sandbox Code Playgroud)
我有一个字符串,我需要知道列表中任何成员的总出现次数:
stripe = 1,rope = 0 ,, rprpraxp = 4等
现在我可以循环计算每个成员出现次数的列表成员,然后将它们合计,如下所示:
sublist = ['x', 'str', 'a', 'pr']
string = "rprpraxp"
inst = 0
for member in sublist:
inst = inst + string.count(member)
print(inst)
Run Code Online (Sandbox Code Playgroud)
但是我想知道我是否错过了一个更短,更简单,更直观和更Pythonic的方法来计算另一个字符串中的一组项目的成员,如:
inst = string.multicount(['x', 'str', 'a', 'pr'])
Run Code Online (Sandbox Code Playgroud)
这样的事情存在吗?
谢谢.
所以我还在学习Python,我正在学习如何阅读文件,csv文件.我刚看过的课程告诉我使用
csv.reader(filename)
Run Code Online (Sandbox Code Playgroud)
返回一个列表.
所以我写了下面的代码:
import csv
my_file = open(file_name.csv, mode='r')
parsed_data = csv.reader(my_file)
print(parsed_data)
Run Code Online (Sandbox Code Playgroud)
它打印的是什么
<_csv.reader object at 0x0000000002838118>
Run Code Online (Sandbox Code Playgroud)
如果它输出的是一个列表,我不应该得到一个列表,即这样的东西?
[value1, value2, value3]
Run Code Online (Sandbox Code Playgroud) 我刚刚开始使用Python,我刚刚接触过装饰器.我写了下面的代码,模仿我所看到的,它的工作原理:
def decorator_function(passed_function):
def inner_decorator():
print('this happens before')
passed_function()
print('this happens after')
return inner_decorator
@decorator_function
def what_we_call():
print('The actual function we called.')
what_we_call()
Run Code Online (Sandbox Code Playgroud)
但后来我写了这个,这会引发错误:
def decorator_function(passed_function):
print('this happens before')
passed_function()
print('this happens after')
@decorator_function
def what_we_call():
print('The actual function we called.')
what_we_call()
Run Code Online (Sandbox Code Playgroud)
那么,为什么我们需要在装饰器函数中包含内部嵌套函数?它的用途是什么?使用第二种语法不是更简单吗?我得不到什么?
有趣的是,BOTH具有相同(正确)的输出,但第二个也有错误文本,说"TypeError:'NoneType'对象不可调用"
请使用适合刚开始使用Python的语言和示例,这是他的第一个编程语言 - 也是OOP的新手!:) 谢谢.
我知道我可以这样做:
z = a if switch == 1 else z = b
Run Code Online (Sandbox Code Playgroud)
但如果我想要z=a if switch=1, z=b if switch=2, and z=c if switch=3怎么办?是否有一种python有效的方法将其写为单行?
就像是:
z = a if switch == 1 else z = b if switch == 2 else z = c
谢谢,现在只是学习Python(显然).
python ×5
csv ×1
decorator ×1
dictionary ×1
if-statement ×1
inline ×1
integer ×1
key ×1
python-3.x ×1
string ×1