[英]Converting list of strings to list of tuples
I want to convert a list [bird, cake, day]
to [(bird, 4), (cake, 4), (day, 3)]
which is [(element, len(element))]
format.我想将列表
[bird, cake, day]
为[(bird, 4), (cake, 4), (day, 3)]
这是[(element, len(element))]
格式。
I did我做了
for element in a_list:
element = tuple(element, len(element))
but getting tuple() takes at most 1 argument (2 given) error.但是获取 tuple() 最多需要 1 个参数(给定 2 个)错误。
How can I fix this?我怎样才能解决这个问题?
your getting that error because your passing two args to tuple(), this should work:您收到该错误是因为您将两个 args 传递给 tuple(),这应该有效:
[tuple((element, len(element))) for element in a_list]
or shorter:或更短:
[(element, len(element)) for element in a_list]
lst1 = ['bird', 'cake', 'day']
lst2 = [(i, len(i)) for i in lst1]
print(lst2)
OUT:出去:
[('bird', 4), ('cake', 4), ('day', 3)]
I assumed your a_list
is string.我假设你的
a_list
是字符串。 This works.这有效。
a_list = ["bird", "cake", "day"]
new_list = []
for element in a_list:
new_list.append([element, len(element)])
print(new_list)
[['bird', 4], ['cake', 4], ['day', 3]] [['鸟', 4], ['蛋糕', 4], ['天', 3]]
The reason your code is not working is you updating the element
reference in the for loop.您的代码不起作用的原因是您更新了 for 循环中的
element
引用。 Which is not an identical reference to the value in the a_list
.这与
a_list
的值不同。
Try this using list comprehension:使用列表理解试试这个:
element = ["bird", "cake", "day"]
new_list = [(i, len(i)) for i in element]
print(new_list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.