简体   繁体   English

Python:添加元组的解压缩值(字符串)

[英]Python: Adding unpacked values (strings) of a tuple

Is there a single line command to add two strings contained in a tuple to two existing strings in a program?是否有单行命令将元组中包含的两个字符串添加到程序中的两个现有字符串?

This is essentially what I want to do but in a shorter way,这基本上是我想要做的,但以更短的方式,

t=("hi","hello")
x="test"
y="python"
x+=t[0]
y+=t[1]

I was thinking maybe there is a code like this that actually works,我在想也许有这样的代码确实有效,

x+,y+=t

Using python's in place addition with unpacked tuples - I really liked the complex number solution given in this similar question, but I cannot use it since my values are strings. 将 python 的就地加法与未打包的元组一起使用——我真的很喜欢这个类似问题中给出的复数解决方案,但我不能使用它,因为我的值是字符串。 Or is there a way I can manipulate my data (without going into too many lines of code) so that this method can be used?或者有没有一种方法可以操纵我的数据(无需进入太多代码行)以便可以使用这种方法?

Using this answer from the question you linked, you can do this:使用您链接的问题答案,您可以这样做:

from operator import add

t = ("hi", "hello")
x = "test"
y = "python"

x, y = map(add, (x, y), t)

Honestly, it is rather hard to read and I would advise against using it.老实说,它很难阅读,我建议不要使用它。 As far as default Python syntax goes, I doubt there is anything you could use.就默认的 Python 语法而言,我怀疑有什么可以使用的。

A single line of code doing what you expect is given below,下面给出了执行您期望的单行代码,

Code:代码:

x, y = ["".join(i) for i in zip([x,y], t)]

Here zip() makes an iterator which aggregates the elements from each of the sequences passed to it.这里zip()创建了一个迭代器,它聚合来自每个传递给它的序列的元素。 In this case it would be [(x, t[0]), (y, t[1])] .在这种情况下,它将是[(x, t[0]), (y, t[1])] .join() concatenates the elements of the list passed to it with a separator ( "" in this case). .join()将传递给它的列表元素与分隔符(在本例中为"" )连接起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM