list.append()是添加到列表末尾的明显选择.这是对失踪人员的合理解释list.prepend().假设我的列表很短并且性能问题可以忽略不计,那就是
list.insert(0, x)
Run Code Online (Sandbox Code Playgroud)
要么
list[0:0] = [x]
Run Code Online (Sandbox Code Playgroud)
地道?
我正在学习Python 3.4.2中的函数和类,我从这段代码片段的输出中得到了一些偏见:
print("This program will collect your demographic information and output it")
print ("")
class Demographics: #This class contains functions to collect demographic info
def phoneFunc(): #This function will collect user's PN, including area code
phoneNum = str(input("Enter your phone number, area code first "))
phoneNumList = []
phoneNumList[:0] = phoneNum
#phoneNumList.insert(0, phoneNum) this is commented out b/c I tried this and it made the next two lines insert the dash incorrectly
phoneNumList.insert(3, '-')
phoneNumList.insert(7, '-')
print(*phoneNumList)
x = Demographics …Run Code Online (Sandbox Code Playgroud) 我在 Python 中有一个名为“AllLines”的二维数组
[['Suppliers', 'Spend', 'Test Field\n'],
['Dell Inc', '9000', '1\n'],
['Dell Computers', '9000', '2\n'],
['HBC Corp', '9000', '3\n'],
['HBC INC', '9000', '4']]
Run Code Online (Sandbox Code Playgroud)
所以,它是一个数组中的一个数组。我需要将项目附加到内部数组。给我这个:
[['NEW','Suppliers', 'Spend', 'Test Field\n'],
['N-E-W','Dell Inc', '9000', '1\n'],
['N-E-W---','Dell Computers', '9000', '2\n'],
['N-E---W','HBC Corp', '9000', '3\n'],
['N-W-W','HBC INC', '9000', '4']]
Run Code Online (Sandbox Code Playgroud)
如何实现向内部数组添加新项目?