将变量添加到元组

问题:将变量添加到元组

我正在学习Python并创建数据库连接。在尝试添加到数据库时,我正在考虑从信息中创建元组,然后将其添加到数据库中。

我正在做什么:我正在从用户那里获取信息并将其存储在变量中。我可以将这些变量添加到元组吗?您能帮我语法吗?

另外,如果有有效的方法,请分享…

编辑 让我稍微编辑一下这个问题…我只需要元组即可将信息输入数据库。将信息添加到数据库后,是否应该删除元组?我的意思是我不再需要元组了。

I am learning Python and creating a database connection. While trying to add to the DB, I am thinking of creating tuples out of information and then add them to the DB.

What I am Doing: I am taking information from the user and store it in variables. Can I add these variables into a tuple? Can you please help me with the syntax?

Also if there is an efficient way of doing this, please share…

EDIT Let me edit this question a bit…I only need the tuple to enter info into the DB. Once the information is added to the DB, should I delete the tuple? I mean I don’t need the tuple anymore.


回答 0

元组是不可变的;您无法在构造后更改它们包含的变量。但是,您可以将它们串联或切片以形成新的元组:

a = (1, 2, 3)
b = a + (4, 5, 6)  # (1, 2, 3, 4, 5, 6)
c = b[1:]  # (2, 3, 4, 5, 6)

并且,当然,要根据现有价值来构建它们:

name = "Joe"
age = 40
location = "New York"
joe = (name, age, location)

Tuples are immutable; you can’t change which variables they contain after construction. However, you can concatenate or slice them to form new tuples:

a = (1, 2, 3)
b = a + (4, 5, 6)  # (1, 2, 3, 4, 5, 6)
c = b[1:]  # (2, 3, 4, 5, 6)

And, of course, build them from existing values:

name = "Joe"
age = 40
location = "New York"
joe = (name, age, location)

回答 1

您可以从类似的空白元组开始t = ()。您可以添加+,但必须添加另一个元组。如果要添加单个元素,请使其成为单例:t = t + (element,)。您可以添加带有或不带有逗号的多个元素的元组。

>>> t = ()
>>> t = t + (1,)
>>> t
(1,)
>>> t = t + (2,)
>>> t
(1, 2)
>>> t = t + (3, 4, 5)
>>> t
(1, 2, 3, 4, 5)
>>> t = t + (6, 7, 8,)
>>> t
(1, 2, 3, 4, 5, 6, 7, 8)

You can start with a blank tuple with something like t = (). You can add with +, but you have to add another tuple. If you want to add a single element, make it a singleton: t = t + (element,). You can add a tuple of multiple elements with or without that trailing comma.

>>> t = ()
>>> t = t + (1,)
>>> t
(1,)
>>> t = t + (2,)
>>> t
(1, 2)
>>> t = t + (3, 4, 5)
>>> t
(1, 2, 3, 4, 5)
>>> t = t + (6, 7, 8,)
>>> t
(1, 2, 3, 4, 5, 6, 7, 8)

回答 2

尚未提及的另一种策略是使用追加到列表,然后在最后将列表转换为元组:

mylist = []
for x in range(5):
    mylist.append(x)
mytuple = tuple(mylist)
print mytuple

退货

(0, 1, 2, 3, 4)

当我必须将元组作为函数参数传递时,有时会使用此函数,这对于numpy函数通常是必需的。

Another tactic not yet mentioned is using appending to a list, and then converting the list to a tuple at the end:

mylist = []
for x in range(5):
    mylist.append(x)
mytuple = tuple(mylist)
print mytuple

returns

(0, 1, 2, 3, 4)

I sometimes use this when I have to pass a tuple as a function argument, which is often necessary for the numpy functions.


回答 3

在Python 3中,您可以用来*根据原始元组以及新元素创建一个新的元组元素。

>>> tuple1 = ("foo", "bar")
>>> tuple2 = (*tuple1, "baz")
>>> tuple2
('foo', 'bar', 'baz')

In Python 3, you can use * to create a new tuple of elements from the original tuple along with the new element.

>>> tuple1 = ("foo", "bar")
>>> tuple2 = (*tuple1, "baz")
>>> tuple2
('foo', 'bar', 'baz')

The byte code is almost the same as tuple1 + ("baz",)

Python 3.7.5 (default, Oct 22 2019, 10:35:10) 
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...     tuple1 = ("foo", "bar")
...     tuple2 = (*tuple1, "baz")
...     return tuple2
... 
>>> def g():
...     tuple1 = ("foo", "bar")
...     tuple2 = tuple1 + ("baz",)
...     return tuple2
... 
>>> from dis import dis
>>> dis(f)
  2           0 LOAD_CONST               1 (('foo', 'bar'))
              2 STORE_FAST               0 (tuple1)

  3           4 LOAD_FAST                0 (tuple1)
              6 LOAD_CONST               3 (('baz',))
              8 BUILD_TUPLE_UNPACK       2
             10 STORE_FAST               1 (tuple2)

  4          12 LOAD_FAST                1 (tuple2)
             14 RETURN_VALUE
>>> dis(g)
  2           0 LOAD_CONST               1 (('foo', 'bar'))
              2 STORE_FAST               0 (tuple1)

  3           4 LOAD_FAST                0 (tuple1)
              6 LOAD_CONST               2 (('baz',))
              8 BINARY_ADD
             10 STORE_FAST               1 (tuple2)

  4          12 LOAD_FAST                1 (tuple2)
             14 RETURN_VALUE

The only difference is BUILD_TUPLE_UNPACK vs BINARY_ADD. The exact performance depends on the Python interpreter implementation, but it’s easier to implement BUILD_TUPLE_UNPACK fast than BINARY_ADD because BINARY_ADD is a polymorphic operator, requiring additional type calculation and implicit conversion.


回答 4

“一旦信息添加到数据库,我应该删除元组吗?我的意思是我不再需要元组。”

没有。

通常,没有理由删除任何内容。有一些特殊情况需要删除,但是非常罕见。

只需定义一个狭窄的范围(即类中的函数定义或方法函数),对象就会在范围的末尾被垃圾回收。

不用担心删除任何内容。

[注意。我曾与一个人合作,除了试图删除对象外,他还一直在编写“重置”方法来清除它们。就像他要保存它们并重用它们一样。也是一个愚蠢的自负。只需忽略不再使用的对象。如果用足够小的代码块定义函数,就没有什么要考虑的了。]

” once the info is added to the DB, should I delete the tuple? i mean i dont need the tuple anymore.”

No.

Generally, there’s no reason to delete anything. There are some special cases for deleting, but they’re very, very rare.

Simply define a narrow scope (i.e., a function definition or a method function in a class) and the objects will be garbage collected at the end of the scope.

Don’t worry about deleting anything.

[Note. I worked with a guy who — in addition to trying to delete objects — was always writing “reset” methods to clear them out. Like he was going to save them and reuse them. Also a silly conceit. Just ignore the objects you’re no longer using. If you define your functions in small-enough blocks of code, you have nothing more to think about.]


回答 5

如下所示:

info_1 = "one piece of info"
info_2 = "another piece"
vars = (info_1, info_2)
# 'vars' is now a tuple with the values ("info_1", "info_2")

但是,Python中的元组是不可变的,因此一旦创建元组,就不能将变量追加到元组中。

It’s as easy as the following:

info_1 = "one piece of info"
info_2 = "another piece"
vars = (info_1, info_2)
# 'vars' is now a tuple with the values ("info_1", "info_2")

However, tuples in Python are immutable, so you cannot append variables to a tuple once it is created.


回答 6

正如其他答案所指出的那样,您无法更改现有的元组,但始终可以创建一个新的元组(该元组可能会从现有的元组和/或其他来源中获取部分或全部项目)。

例如,如果所有感兴趣的项都在标量变量中,并且您知道这些变量的名称,则:

def maketuple(variables, names):
  return tuple(variables[n] for n in names)

使用,例如,在本示例中:

def example():
  x = 23
  y = 45
  z = 67
  return maketuple(vars(), 'x y z'.split())

当然,这一种情况将更简单地表示为(x, y, z)(或什至完全不使用名称(23, 45, 67)),但是该maketuple方法在一些更复杂的情况下可能很有用(例如,要使用的名称也是动态确定的,并在使用过程中附加到列表中)。计算)。

As other answers have noted, you cannot change an existing tuple, but you can always create a new tuple (which may take some or all items from existing tuples and/or other sources).

For example, if all the items of interest are in scalar variables and you know the names of those variables:

def maketuple(variables, names):
  return tuple(variables[n] for n in names)

to be used, e.g, as in this example:

def example():
  x = 23
  y = 45
  z = 67
  return maketuple(vars(), 'x y z'.split())

of course this one case would be more simply expressed as (x, y, z) (or even foregoing the names altogether, (23, 45, 67)), but the maketuple approach might be useful in some more complicated cases (e.g. where the names to use are also determined dynamically and appended to a list during the computation).


回答 7

我很确定python中的语法是:

user_input1 = raw_input("Enter Name: ")
user_input2 = raw_input("Enter Value: ")
info = (user_input1, user_input2)

一旦设置,元组就不能更改。

I’m pretty sure the syntax for this in python is:

user_input1 = raw_input("Enter Name: ")
user_input2 = raw_input("Enter Value: ")
info = (user_input1, user_input2)

once set, tuples cannot be changed.