如何在开头将一个字符串附加到列表中的每个元组?

时间:2017-10-10 11:20:09

标签: string python-3.x tuples

 tuple_list = [('1','2'),('2','3'),('2','6')]
 string = Point

 Desired_List = [Point('1','2'),Point('2','3'),Point('2','6')]

我尝试过以下代码:

   for x in tuple_list:
    x.append("Point")

   for x in tuple_list:
    x + 'Point'

如何将开头的字符串附加到列表中的每个元组?

更新您的信息,我在x和y点的csv文件中有2列和数百行:

x    y
1    3
2    4

我希望得到:

Points = [Point(1,3),Point(2,4),......]

1 个答案:

答案 0 :(得分:0)

如果你需要字符串,这就是要走的路:

desired_list = []
for x,y in tuple_list:
    desired_list.append(f"Point({x},{y})")

产生以下输出:

>>> print(desired_list)
['Point(1,2)', 'Point(2,3)', 'Point(2,6)']

就名称元组而言,您可以按照以下方式执行此操作:

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
tuple_list = [('1','2'),('2','3'),('2','6')]
desired_list = []
for x,y in tuple_list:
    desired_list.append(Point(x, y))

相应的结果是:

>>> print(desired_list)
[Point(x='1', y='2'), Point(x='2', y='3'), Point(x='2', y='6')]