SORU
9 Temmuz 2010, Cuma


Eğer x listede ise, neden x = &; ha" iş " iken x = x "ha" bir istisna atar mı?

Bildiğim kadarıyla listeler için op sadece 2 işlenen iterable olması gerekir, "" net. ha

Kod:

>>> x = []
>>> x  = "ha"
>>> x
['h', 'a']
>>> x = x   "ha"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list

CEVAP
9 Temmuz 2010, Cuma


Listesi = extend, değil " demesi gibi.

  • Bir iterable extend diyebilirsin.
  • Sadece başka bir liste ile kullanabilirsiniz.

Sadece bu kararın nedenini tahmin edebiliyorum, ama performansla ilgili nedenlerden dolayı olduğunu tahmin ediyorum. Yeni bir nesne oluşturuldu arama sonuçları ve tüm öğeleri extend mevcut listesinde boş alanı kullanabilir ise kopyalanan, bazı durumlarda bir kopyasını kaydetme nesne.

Bu kararın yan etkisi başka bir x = x y kullanırsanız listeye x = y diğer referanslar değişiklik görürsünüz yazarsan ancak o zaman onlar. Bu aşağıda gösterilmiştir:

>>> x = ['a','b']
>>> y = ['c', d']
>>> z = x
>>> x  = y
>>> z
['a', 'b', 'c', 'd']

>>> x = ['a','b']
>>> y = ['c', d']
>>> z = x
>>> x = x   y
>>> z
['a', 'b']

Referanslar

Python source code for list.

Kaynak = için: kod

static PyObject *
list_inplace_concat(PyListObject *self, PyObject *other)
{
    PyObject *result;

    result = listextend(self, other);
    if (result == NULL)
        return result;
    Py_DECREF(result);
    Py_INCREF(self);
    return (PyObject *)self;
}

Kaynak : kodu

static PyObject *
list_concat(PyListObject *a, PyObject *bb)
{
    Py_ssize_t size;
    Py_ssize_t i;
    PyObject **src, **dest;
    PyListObject *np;
    if (!PyList_Check(bb)) {
        PyErr_Format(PyExc_TypeError,
                  "can only concatenate list (not \"%.200s\") to list",
                  bb->ob_type->tp_name);
        return NULL;
    }

    // etc ...

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • OVERWERK

    OVERWERK

    6 Temmuz 2010
  • RaverX DouBle StAg XI

    RaverX DouBl

    23 Mayıs 2008
  • VvCompHelpvV

    VvCompHelpvV

    4 EYLÜL 2007