add reversed&pop

This commit is contained in:
blueloveTH 2022-12-09 00:48:00 +08:00
parent 609d7e68d8
commit db9ce1dbfc
3 changed files with 34 additions and 10 deletions

View File

@ -64,6 +64,13 @@ def __list4index(self, value):
list.index = __list4index list.index = __list4index
del __list4index del __list4index
def __list4pop(self, i=-1):
res = self[i]
del self[i]
return res
list.pop = __list4pop
del __list4pop
def __list4__mul__(self, n): def __list4__mul__(self, n):
a = [] a = []
for i in range(n): for i in range(n):
@ -222,6 +229,10 @@ def map(f, iterable):
def zip(a, b): def zip(a, b):
return [(a[i], b[i]) for i in range(min(len(a), len(b)))] return [(a[i], b[i]) for i in range(min(len(a), len(b)))]
def reversed(iterable):
a = list(iterable)
return [a[i] for i in range(len(a)-1, -1, -1)]
def sorted(iterable, key=None, reverse=False): def sorted(iterable, key=None, reverse=False):
if key is None: if key is None:
key = lambda x: x key = lambda x: x

View File

@ -461,15 +461,6 @@ void __initializeBuiltinFunctions(VM* _vm) {
return vm->PyList(vm->PyList_AS_C(args[0])); return vm->PyList(vm->PyList_AS_C(args[0]));
}); });
_vm->bindMethod("list", "pop", [](VM* vm, const pkpy::ArgList& args) {
vm->__checkArgSize(args, 1, true);
PyVarList& _self = vm->PyList_AS_C(args[0]);
if(_self.empty()) vm->indexError("pop from empty list");
PyVar ret = _self.back();
_self.pop_back();
return ret;
});
_vm->bindMethod("list", "__add__", [](VM* vm, const pkpy::ArgList& args) { _vm->bindMethod("list", "__add__", [](VM* vm, const pkpy::ArgList& args) {
const PyVarList& _self = vm->PyList_AS_C(args[0]); const PyVarList& _self = vm->PyList_AS_C(args[0]);
const PyVarList& _obj = vm->PyList_AS_C(args[1]); const PyVarList& _obj = vm->PyList_AS_C(args[1]);

View File

@ -6,3 +6,25 @@ assert a == [0, 2, 4, 6, 8]
a = [i**3 for i in range(10) if i % 2 == 0] a = [i**3 for i in range(10) if i % 2 == 0]
assert a == [0, 8, 64, 216, 512] assert a == [0, 8, 64, 216, 512]
a = [1, 2, 3, 4]
assert a.pop() == 4
assert a == [1, 2, 3]
assert a.pop(0) == 1
assert a == [2, 3]
assert a.pop(-2) == 2
assert a == [3]
a = [1, 2, 3, 4]
assert reversed(a) == [4, 3, 2, 1]
assert a == [1, 2, 3, 4]
a = (1, 2, 3, 4)
assert reversed(a) == [4, 3, 2, 1]
assert a == (1, 2, 3, 4)
a = '1234'
assert reversed(a) == ['4', '3', '2', '1']
assert a == '1234'
assert reversed([]) == []
assert reversed('') == []
assert reversed('测试') == ['', '']