2017-10-10 29 views
0
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),......] 
+3

您不能追加一个字符串一个元组的开始 - 那些是[NamedTuples](https://docs.python.org/3/library/collections.html#collections.namedtuple) – SiHa

+0

可以定义一个快速的'class Point:def __init __(self): self.x = None,self.y = None'并且有你的对象列表。 – pstatix

+1

这是什么'Desired_List'应该是?那个'Point'应该是什么?在你的例子中,它看起来像你为每个元组实例化的类,它与你所要求的元组或字符串操作无关。请改进该示例代码,以便了解发生了什么。有关更多信息,请参阅[PEP 8命名约定](https://www.python.org/dev/peps/pep-0008/#naming-conventions)。 – Jeronimo

回答

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')] 
相关问题