Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
如果我有变量xand y,那么:
x
y
如何创建列表z == [x, <all elements of y>]?
z == [x, <all elements of y>]
例如:
x = 'x' y = 'y' # create z assert z == ['x', 'y']
x = 'x' y = ['y', 'y2'] # create z assert z == ['x', 'y', 'y2']
z = [x] + (y if isinstance(y, list) else [y])
不过,通常我会避免使用y可能是字符串或列表的 a :这似乎没有必要。
z = [x] if isinstance(y, list): z.extend(y) else: z.append(y)
import itertools z = itertools.chain(x, y)