日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

python中如何使用函數(shù)改變list_python

作者:健忘紳士辣雞君 ? 更新時間: 2022-11-16 編程語言

python使用函數(shù)改變list

函數(shù)內(nèi)改變外部的一個list如果這么寫

def rotate(nums, k):
? ? length=len(nums)
? ? if length!=0:
? ? ? ? nums=nums[length-k:length]+nums[0:length-k]
?
l=[1,2,3,4,5,6,7]
rotate(l,3)
print(l)

外部的list并沒有改變,而返回的是[1, 2, 3, 4, 5, 6, 7]

要改變list中的內(nèi)容需要這么寫

def rotate(nums, k):
? ? length=len(nums)
? ? if length!=0:
? ? ? ? nums[:]=nums[length-k:length]+nums[0:length-k]
?
l=[1,2,3,4,5,6,7]
rotate(l,3)
print(l)

這樣就返回的是[5, 6, 7, 1, 2, 3, 4]

python list函數(shù)用法

描述

list()函數(shù)是Python的內(nèi)置函數(shù)。它可以將任何可迭代數(shù)據(jù)轉(zhuǎn)換為列表類型,并返回轉(zhuǎn)換后的列表。當(dāng)參數(shù)為空時,list函數(shù)可以創(chuàng)建一個空列表。

語法

list(object)

名稱 說明 備注
object 待轉(zhuǎn)換為列表的數(shù)據(jù)類型 可省略的參數(shù)

使用示例

1. 創(chuàng)建一個空列表(無參調(diào)用list函數(shù))

>>> test = list()
>>> test
[]

2. 將字符串轉(zhuǎn)換為列表

>>> test = list('cat')
>>> test
['c', 'a', 't']

3. 將元組轉(zhuǎn)換為列表

>>> a_tuple = ('I love Python.', 'I also love HTML.')
>>> test = list(a_tuple)
>>> test
['I love Python.', 'I also love HTML.']

4. 將字典轉(zhuǎn)換為列表

>>> a_dict = {'China':'Beijing', 'Russia':'Moscow'}
>>> test = list(a_dict)
>>> test
['China', 'Russia']

??注意:將字典轉(zhuǎn)換為列表時,會將字典的值舍去,而僅僅將字典的鍵轉(zhuǎn)換為列表。如果想將字典的值全部轉(zhuǎn)換為列表,可以考慮使用字典方法dict.values()

5. 將集合轉(zhuǎn)換為列表

>>> a_set = {1, 4, 'sdf'}
>>> test = list(a_set)
>>> test
[1, 'sdf', 4]

6. 將其他可迭代序列轉(zhuǎn)化為列表

下面的代碼將range類型和map類型的可迭代序列轉(zhuǎn)換為列表:

>>> test1 = list(range(10))
>>> test2 = list(map(int, [23.2, 33.1]))
>>> test1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test2
[23, 33]

注意事項(xiàng)

1. 參數(shù)必須是可迭代序列對象

list函數(shù)的參數(shù)必須是可迭代對象。當(dāng)選用不可迭代的對象作為參數(shù)時,Python報錯。

>>> test = list(12)
Traceback (most recent call last):
? File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

將列表轉(zhuǎn)換為列表

可以使用list函數(shù)將列表轉(zhuǎn)換為一個列表,這么做Python不會有任何的異常或者報錯。它的作用是將參數(shù)列表進(jìn)行深拷貝:

if __name__ == '__main__':
    source_list = ["a", "b", "c", "d"]
    new_list1 = list(source_list)
    print(id(source_list), id(new_list1))
    # output: 4313597760 4312890304
 
    new_list2 = source_list
    print(new_list1)
    # output: ['a', 'b', 'c', 'd']
    print(new_list2)
    # output: ['a', 'b', 'c', 'd']
 
    source_list[0] = "e"
    print(new_list1)
    # output: ['a', 'b', 'c', 'd']
    print(new_list2)
    # output: ['e', 'b', 'c', 'd']

原文鏈接:https://blog.csdn.net/why12345678901/article/details/81271728

欄目分類
最近更新