在Python中将元组元素附加到元组元组

时间:2016-05-22 21:40:39

标签: python tuples

如果我有一个元组,例如x = (1, 2, 3)我希望将每个元素附加到元组元组的每个元组的前面,例如y = (('a', 'b'), ('c', 'd'), ('e', 'f'))所以最终结果是z = ((1, 'a', 'b'), (2, 'c', 'd'), (3, 'e', 'f')),最简单的方法是什么?

我的第一个想法是zip(x,y),但这会产生((1, ('a', 'b')), (2, ('c', 'd')), (3, ('e', 'f')))

2 个答案:

答案 0 :(得分:2)

// has a delay in the initial few moments without moving, then jumps to it's position and thereafter runs perfectly smooth even after another button press
    public void test()
    {
        Task.Run(() =>
        {
            for (int x = 0; x < 100; x++)
            {
                this.Dispatcher.Invoke((() =>
                {
                    var margin = RectObj.Margin;
                    margin.Left = testValue++;
                    RectObj.Margin = margin;
                }));
                Thread.Sleep(10);
            }
        });
    }
    // runs, but jagged movements/refreshing
    public void test2()
    {
        Task.Run(() =>
        {
            for (int x = 0; x < 100; x++)
            {
                this.Dispatcher.Invoke((() =>
                {
                    var margin = RectObj.Margin;
                    margin.Left = testValue++;
                    RectObj.Margin = margin;
                    Thread.Sleep(10);
                }));
            }
        });
    }
    // does not update display until task is completed
    public void test3()
    {
        Task.Run(() =>
        {
            this.Dispatcher.Invoke((() =>
            {
                for (int x = 0; x < 100; x++)
                {
                    var margin = RectObj.Margin;
                    margin.Left = testValue++;
                    RectObj.Margin = margin;
                    Thread.Sleep(10);
                }
            }));
        });
    }

或者

tuple((num, ) + other for num, other in zip(x, y))

答案 1 :(得分:2)

使用zip并展平结果:

>>> x = (1, 2, 3)
>>> y = (('a', 'b'), ('c', 'd'), ('e', 'f'))
>>> tuple((a, b, c) for a, (b, c) in zip(x,y))
((1, 'a', 'b'), (2, 'c', 'd'), (3, 'e', 'f'))

或者,如果您使用的是Python 3.5,请按照样式执行:

>>> tuple((head, *tail) for head, tail in zip(x,y))
((1, 'a', 'b'), (2, 'c', 'd'), (3, 'e', 'f'))