当前分类:300例题>>正文

Python示例:将项目附加到列表

来源:互联网   更新时间:2023年6月21日  

Python 示例

编写一个 Python示例,将一个项目附加到列表中。在 Python 中,我们有多个选项可以向列表中追加或添加一个项目,这里,我们使用 append 方法。list append 方法在列表的末尾添加一个新元素。

【追加(项)

numbers = [10, 20, 30, 40, 50]

print("Numeric List Before Appending Item")
print(numbers)

numbers.append(65)

print("Numeric List After Appending First Item")
print(numbers)

value = int(input("Please enter the List Item = "))
numbers.append(value)

print("Numeric List After Appending Second Item")
print(numbers)

这个 python 程序使用索引函数将一个项目附加到列表中。list index 方法在指定的索引处添加一个 list 元素。

list.insert(索引,项目)

countries = ["India", "USA", "UK", "Italy"]

print("List Before Appending Item")
print(countries)

countries.insert(3, "Japan")
print("\nList After Appending Japan at 3rd Index Position")
print(countries)

countries.insert(0, "China")
print("\nList After Appending China at 0 Index Position")
print(countries)

countries.insert(6, "France")
print("\nList After Appending France at 6 Index Position")
print(countries)
List Before Appending Item
['India', 'USA', 'UK', 'Italy']

List After Appending Japan at 3rd Index Position
['India', 'USA', 'UK', 'Japan', 'Italy']

List After Appending China at 0 Index Position
['China', 'India', 'USA', 'UK', 'Japan', 'Italy']

List After Appending France at 6 Index Position
['China', 'India', 'USA', 'UK', 'Japan', 'Italy', 'France']

这个 Python 示例允许输入列表索引和列表值,并使用索引方法添加新项目。

numbers = [11, 22, 33, 44, 55, 66]

print("Numeric List Before Inserting Item")
print(numbers)

index = int(input("Please enter Index Position = "))
value = int(input("Please enter the List Value = "))

numbers.insert(index, value)

print("Numeric List After Appending Item")
print(numbers)
Numeric List Before Inserting Item
[11, 22, 33, 44, 55, 66]
Please enter Index Position = 4
Please enter the List Value = 111
Numeric List After Appending Item
[11, 22, 33, 44, 111, 55, 66]

Python示例使用扩展方法将一个项目附加到列表中

list extend 方法将列表、元组、字符串等任何可条目添加到现有列表的末尾。

list.extend(迭代器)

countries = ["India", "USA", "UK", "Italy"]

print("List Before Appending Item")
print(countries)

tuple1 = ("Japan", "China", "France")
countries.extend(tuple1)
print("\nList After Appending Tuple using extend")
print(countries)

list1 = [19, 17, 39, 55]
countries.extend(list1)
print("\nList After Appending List sing extend")
print(countries)

countries.extend((11.5, 19.2))
print("\nList After Appending 11.5, 19.2 using extend")
print(countries)
List Before Appending Item
['India', 'USA', 'UK', 'Italy']

List After Appending Tuple using extend
['India', 'USA', 'UK', 'Italy', 'Japan', 'China', 'France']

List After Appending List sing extend
['India', 'USA', 'UK', 'Italy', 'Japan', 'China', 'France', 19, 17, 39, 55]

List After Appending 11.5, 19.2 using extend
['India', 'USA', 'UK', 'Italy', 'Japan', 'China', 'France', 19, 17, 39, 55, 11.5, 19.2]
本文固定链接:https://6yhj.com/leku-p-4374.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: 采集