为什么我不能在Python中使用"+"运算符将元组添加到列表中? [英] Why can't I add a tuple to a list with the '+' operator in Python?

查看:347
本文介绍了为什么我不能在Python中使用"+"运算符将元组添加到列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python不支持将元组添加到列表:

Python not support adding a tuple to a list:

>>> [1,2,3] + (4,5,6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "tuple") to list

以这种语言提供这种支持有哪些不利条件?请注意,我希望这是对称的:[1, 2] + (3, 4)(1, 2) + [3, 4]都将评估为一个全新的列表[1, 2, 3, 4].我的理由是,一旦有人将运算符+应用于元组和列表的混合,他们很可能会再次执行此操作(很有可能在同一表达式中),因此我们也可能会提供列表以避免额外的转换.

What are the disadvantages for providing such a support in the language? Note that I would expect this to be symmetric: [1, 2] + (3, 4) and (1, 2) + [3, 4] would both evaluate to a brand-new list [1, 2, 3, 4]. My rationale is that once someone applied operator + to a mix of tuples and lists, they are likely to do it again (very possibly in the same expression), so we might as well provide the list to avoid extra conversions.

这是我问这个问题的动机.

Here's my motivation for this question.

我经常会收藏一些较小的收藏,而我更喜欢将它们存储为元组,以避免意外修改并提高性能.然后,我需要将这样的元组与列表结合起来,并且不得不将每个元组转换为列表,这使得代码非常难看.

It happens quite often that I have small collections that I prefer to store as tuples to avoid accidental modification and to help performance. I then need to combine such tuples with lists, and having to convert each of them to list makes for very ugly code.

请注意,在简单情况下,+=extend可能会起作用.但总的来说,当我有一个表情

Note that += or extend may work in simple cases. But in general, when I have an expression

columns = default_columns + columns_from_user + calculated_columns

我不知道其中哪些是元组,哪些是列表.所以我要么必须将所有内容都转换为列表:

I don't know which of these are tuples and which are lists. So I either have to convert everything to lists:

columns = list(default_columns) + list(columns_from_user) + list(calculated_columns)

或使用itertools:

Or use itertools:

columns = list(itertools.chain(default_columns, columns_from_user, calculated_columns))

这两种解决方案都不是简单的总和.并且chain可能也较慢(因为它必须一次遍历输入中的一个元素).

Both of these solutions are uglier than a simple sum; and the chain may also be slower (since it must iterate through the inputs an element at a time).

推荐答案

不支持此操作,因为+运算符应该是对称的.您期望什么返回类型? Python Zen包含规则

This is not supported because the + operator is supposed to be symmetric. What return type would you expect? The Python Zen includes the rule

In the face of ambiguity, refuse the temptation to guess.

但是,以下工作有效:

a = [1, 2, 3]
a += (4, 5, 6)

在这里使用哪种类型没有歧义.

There is no ambiguity what type to use here.

这篇关于为什么我不能在Python中使用"+"运算符将元组添加到列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆