Python有一个内置函数sum,它实际上相当于:
def sum2(iterable, start=0):
return start + reduce(operator.add, iterable)
Run Code Online (Sandbox Code Playgroud)
除了字符串之外的所有类型的参数.它适用于数字和列表,例如:
sum([1,2,3], 0) = sum2([1,2,3],0) = 6 #Note: 0 is the default value for start, but I include it for clarity
sum({888:1}, 0) = sum2({888:1},0) = 888
Run Code Online (Sandbox Code Playgroud)
为什么特别遗漏了字符串?
sum( ['foo','bar'], '') # TypeError: sum() can't sum strings [use ''.join(seq) instead]
sum2(['foo','bar'], '') = 'foobar'
Run Code Online (Sandbox Code Playgroud)
我似乎记得在Python列表中讨论的原因,所以解释或解释它的线程的链接会很好.
编辑:我知道标准的方法是做"".join.我的问题是为什么禁止对字符串使用sum的选项,并且没有禁止,例如,列表.
编辑2:虽然我认为这不是必需的,但我得到了所有的好答案,问题是:为什么sum在包含数字的迭代或包含列表的迭代但不包含包含字符串的迭代?
... is可用于字符串中相等的关键字.
>>> s = 'str'
>>> s is 'str'
True
>>> s is 'st'
False
Run Code Online (Sandbox Code Playgroud)
我试过了两个__is__(),__eq__()但他们没有工作.
>>> class MyString:
... def __init__(self):
... self.s = 'string'
... def __is__(self, s):
... return self.s == s
...
>>>
>>>
>>> m = MyString()
>>> m is 'ss'
False
>>> m is 'string' # <--- Expected to work
False
>>>
>>> class MyString:
... def __init__(self):
... self.s = 'string'
... def __eq__(self, s):
... return …Run Code Online (Sandbox Code Playgroud) 我写了这个简单的函数:
def padded_hex(i, l):
given_int = i
given_len = l
hex_result = hex(given_int)[2:] # remove '0x' from beginning of str
num_hex_chars = len(hex_result)
extra_zeros = '0' * (given_len - num_hex_chars) # may not get used..
return ('0x' + hex_result if num_hex_chars == given_len else
'?' * given_len if num_hex_chars > given_len else
'0x' + extra_zeros + hex_result if num_hex_chars < given_len else
None)
Run Code Online (Sandbox Code Playgroud)
例子:
padded_hex(42,4) # result '0x002a'
hex(15) # result '0xf'
padded_hex(15,1) # result '0xf'
Run Code Online (Sandbox Code Playgroud)
虽然这对我来说足够清楚并且适合我的用例(一个简单的打印机简单的测试工具),我不禁想到有很大的改进空间,这可以被压缩到非常简洁的东西.
还有哪些方法可以解决这个问题?
如何查找数组中存在的值以及如何删除它.如果任何php内置数组用于执行此操作.删除后我需要顺序索引顺序.任何身体都知道请帮助我.
当我尝试read在Bash中使用这样的命令时:
echo hello | read str
echo $str
Run Code Online (Sandbox Code Playgroud)
什么都没有回应,而我认为str应该包含字符串hello.任何人都可以帮我理解这种行为吗?
如何将文件路径作为字符提取文件的扩展名?我知道我可以通过正则表达式来做到这一点regexpr("\\.([[:alnum:]]+)$", x),但想知道是否有内置函数来处理这个问题?
当我做一些类似的事情时,我感到很沮丧man bindkey:
BUILTIN(1) BSD General Commands Manual BUILTIN(1)
NAME
builtin, !, %, ., :, @, {, }, alias, alloc, bg, bind, bindkey, break, breaksw, builtins, case, cd, chdir, command,
complete, continue, default, dirs, do, done, echo, echotc, elif, else, end, endif, endsw, esac, eval, exec, exit,
export, false, fc, fg, filetest, fi, for, foreach, getopts, glob, goto, hash, hashstat, history, hup, if, jobid,
jobs, kill, limit, local, log, login, logout, ls-F, nice, nohup, notify, onintr, popd, printenv, pushd, … 在Python中有一个名为的内置函数dir.这用于获取对象的所有属性的列表.
我理解它的作用,但我很困惑为什么它被调用dir.这个名称与从对象获取属性有什么关系?
如果我arr = [1, 2, 3, 4]知道我可以做以下事情......
> arr.each_slice(2) { |a, b| puts "#{a}, #{b}" }
1, 2
3, 4
Run Code Online (Sandbox Code Playgroud)
...和...
> arr.each_with_index { |x, i| puts "#{i} - #{x}" }
0 - 1
1 - 2
2 - 3
3 - 4
Run Code Online (Sandbox Code Playgroud)
......但是有没有内置的方法来做到这一点?
> arr.each_slice_with_index(2) { |i, a, b| puts "#{i} - #{a}, #{b}" }
0 - 1, 2
2 - 3, 4
Run Code Online (Sandbox Code Playgroud)
我知道我可以构建自己的并将其粘贴到数组方法中.只是想看看是否有内置功能来做到这一点.
我想像配置文件一样使用.py文件.因此,使用{...}符号我可以使用字符串作为键创建字典,但定义顺序在标准python字典中丢失.
我的问题:是否有可能覆盖{...}符号,以便我得到一个OrderedDict()而不是dict()?
我希望用OrderedDict(dict = OrderedDict)简单地覆盖dict构造函数会起作用,但事实并非如此.
例如:
dict = OrderedDict
dictname = {
'B key': 'value1',
'A key': 'value2',
'C key': 'value3'
}
print dictname.items()
Run Code Online (Sandbox Code Playgroud)
输出:
[('B key', 'value1'), ('A key', 'value2'), ('C key', 'value3')]
Run Code Online (Sandbox Code Playgroud)