[英]Python - How to put tuples into a single list?
I have variables of tuples:我有元组变量:
student1 = ("Allan", "Anderson")
student2 = ("Barry", "Byars")
brendan = ("Brendan","Smith")
sandy = ("Sandy","Garner")
I want to put them in a list:我想把它们放在一个列表中:
students = [("Allan", "Anderson"),("Barry", "Byars")]
How would you do this?你会怎么做? I have 7 variables of tuples and is there an efficient way to do this?
我有 7 个元组变量,有没有一种有效的方法来做到这一点?
I know students.append() can do it but because I have 7 variables, is there a faster way?我知道 students.append() 可以做到,但因为我有 7 个变量,有没有更快的方法?
You should use a better data structure here (like a dictionary):您应该在这里使用更好的数据结构(如字典):
Students = {
"student1": ("Allan", "Anderson"),
"student2": ("Barry", "Byars"),
"brendan": ("Brendan", "Smith"),
"sandy": ("Sandy", "Garner")
}
StudentList = [student for student in Students.values()]
print(StudentList)
Output Output
[('Allan', 'Anderson'), ('Barry', 'Byars'), ('Brendan', 'Smith'), ('Sandy', 'Garner')]
In this way, if you want to add another list you just have to add a single line in your dictionary without changing any logic:这样,如果您想添加另一个列表,您只需在字典中添加一行而不更改任何逻辑:
Students["JohnDoe"] = ("John", "Doe")
Output: Output:
[('Allan', 'Anderson'), ('Barry', 'Byars'), ('Brendan', 'Smith'), ('Sandy', 'Garner'), ('John', 'Doe')]
If there's no structure to your variable names, this is the easiest way.如果您的变量名没有结构,这是最简单的方法。
students = [student1, student2, brendan, sandy]
[('Allan', 'Anderson'), ('Barry', 'Byars'), ('Brendan', 'Smith'), ('Sandy', 'Garner')]
You can define your variables as a dictionary where the keys are the names of the variables.您可以将变量定义为字典,其中键是变量的名称。
For example:例如:
vars_dict = {
"student1": ("Allan", "Anderson"),
"student2": ("Barry", "Byars")
}
and then using dict's values()
method get all values as a list:然后使用 dict 的
values()
方法获取所有值作为列表:
students = list(vars_dict.values())
The simple way to achieve this can be,实现这一目标的简单方法是,
student1 = ("Allan", "Anderson")
student2 = ("Barry", "Byars")
student = [student1, student2]
print(student)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.