In [1]: fruits = ['grape', '@pple', 'strawberry', 'waxberry']
In [2]: fruits.insert(0, 'orange')
In [3]: fruits
Out[3]: ['orange', 'grape', '@pple', 'strawberry', 'waxberry']
In [4]: del fruits[2]
In [5]: fruits
Out[5]: ['orange', 'grape', 'strawberry', 'waxberry']
In [6]: fruits.pop()
Out[6]: 'waxberry'
In [7]: fruits
Out[7]: ['orange', 'grape', 'strawberry']
In [8]: fruits.pop(0)
Out[8]: 'orange'
In [9]: fruits
Out[9]: ['grape', 'strawberry']
In [10]: fruits.remove('apple')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-10-e942fb359de5> in <module>
----> 1 fruits.remove('apple')
ValueError: list.remove(x): x not in list
In [11]: fruits.remove('grape')
In [12]: fruits
Out[12]: ['strawberry']
In [13]: fruits = ['grape', 'apple', 'strawberry', 'waxberry']
In [14]: fruits += ['pitaya', 'pear', 'mango']
In [15]: fruits
Out[15]: ['grape', 'apple', 'strawberry', 'waxberry', 'pitaya', 'pear', 'mango']
In [16]: fruits[::-1] # 直接倒序给出了, 这个操作非常骚气
Out[16]: ['mango', 'pear', 'pitaya', 'waxberry', 'strawberry', 'apple', 'grape']
In [17]: gen = (m + n for m in 'ABCDEFG' for n in '12345')
In [18]: gen
Out[18]: <generator object <genexpr> at 0x050D3540>
In [19]: for elem in gen:
...: print(elem, end=' ')
...:
A1 A2 A3 A4 A5 B1 B2 B3 B4 B5 C1 C2 C3 C4 C5 D1 D2 D3 D4 D5 E1 E2 E3 E4 E5 F1 F2
F3 F4 F5 G1 G2 G3 G4 G5
In [20]: l = [2, 3, 5, 6, 7, 8]
In [21]: import random
In [22]: random.shuffle(l) # 对list随机排序
In [23]: l
Out[23]: [5, 7, 6, 3, 2, 8]
python list 多种操作
最新推荐文章于 2023-10-30 14:49:24 发布