简体   繁体   English

从 Python 中的另一个值列表创建 key,val 的元组列表

[英]Create tuple list of key,val from another list of values in Python

I have the following python list in我有以下python列表

[0,1,2,'def','ghi']

Now I want to convert above into another list of tuples by discarding first list item so for eg I want [(1,0),(2,1),('def',2),('ghi',3)]现在我想通过丢弃第一个列表项将上面转换为另一个元组列表,例如我想要[(1,0),(2,1),('def',2),('ghi',3)]

I have the following code我有以下代码

point = [0,1,2,'def','ghi']
spliltm0 = split[1:]
ls = ()
int i = 0
for a in spliltm0:
   ls = (a,i++)

The above seems to be long code for Python, is there any shorter version of above code?上面似乎是 Python 的长代码,上面的代码有更短的版本吗? I am super new to Python.我是 Python 的新手。

That code isn't Python at all, since you do int i and i++ , neither of which are Python*;该代码根本不是 Python,因为您执行int ii++ ,它们都不是 Python*; also, strip() and split() are methods on strings, not lists.此外, strip()split()是字符串的方法,而不是列表。

Your result can be achieved in a one-line list comprehension:您的结果可以通过单行列表理解来实现:

result = [(elem, i) for i, elem in enumerate(point[1:])]

* i++ is syntactically valid in Python, but doesn't at all do what you think it does. * i++在 Python 中在语法上是有效的,但根本不会做你认为它会做的事情。

You need to be clear about the basics of Python before asking in the Python Forum.在 Python 论坛提问之前,您需要先了解 Python 的基础知识。

1) You cannot apply strip function on a 'list' object, It should be string object. 1) 您不能在“列表”对象上应用 strip 函数,它应该是字符串对象。

2) spliltm0 = split[1:] , Here split is treated as string, and is not defined. 2) spliltm0 = split[1:] ,这里 split 被视为字符串,并没有定义。 Also split is a string method which should not be used as a variable for storing string. split 也是一种字符串方法,不应用作存储字符串的变量。

3) int i = 0 This is a format of C/C++. 3) int i = 0这是C/C++的一种格式。 Not applicable to Python不适用于 Python

4) 4)

for a in spliltm0:
   ls = (a,i++)

i++ is not available in Python. i++ 在 Python 中不可用。 Refer to this link ( Why are there no ++ and --​ operators in Python? )请参阅此链接( 为什么 Python 中没有 ++ 和 -- 运算符?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM