如何传播一个Python数组 - python

This question already has answers here:

How do I concatenate two lists in Python?

(28个答案)

2年前关闭。

在JS我可以做到这一点

const a = [1,2,3,4]
const b = [10, ...a]
console.log(b) // [10,1,2,3,4]

python中有类似的方法吗?

python大神给出的解决方案

正如亚历山大在评论中指出的,列表添加是串联。

a = [1,2,3,4]
b = [10] + a  # N.B. that this is NOT `10 + a`
# [10, 1, 2, 3, 4]

您也可以使用list.extend

a = [1,2,3,4]
b = [10]
b.extend(a)
# b is [10, 1, 2, 3, 4]

较新的Python版本允许您(ab)使用splat(*)运算符。

b = [10, *a]
# [10, 1, 2, 3, 4]

不过,您的选择可能反映了对现有列表进行变异(或不变异)的需求。

a = [1,2,3,4]
b = [10]
DONTCHANGE = b

b = b + a  # (or b += a)
# DONTCHANGE stays [10]
# b is assigned to the new list [10, 1, 2, 3, 4]

b = [*b, *a]
# same as above

b.extend(a)
# DONTCHANGE is now [10, 1, 2, 3, 4]! Uh oh!
# b is too, of course...

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

Python pytz时区函数返回的时区为9分钟 - python

由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

如何打印浮点数的全精度[Python] - python

我编写了以下函数,其中传递了x,y的值:def check(x, y): print(type(x)) print(type(y)) print(x) print(y) if x == y: print "Yes" 现在当我打电话check(1.00000000000000001, 1.0000000000000002)它正在打印:<…

Python:检查新文件是否在文件夹中[重复] - python

This question already has answers here: How do I watch a file for changes? (23个答案) 3年前关闭。 我是python的新手,但是我尝试创建一个自动化过程,其中我的代码将侦听目录中的新文件条目。例如,某人可以手动将zip文件复制到一个特定的文件夹中,并且我希望我的代码能够在文件完全…