Python相当于Haskell的[1 ..](用于索引列表) [英] Python equivalent of Haskell's [1..] (to index a list)

查看:110
本文介绍了Python相当于Haskell的[1 ..](用于索引列表)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python中的元素列表。我不知道列表中元素的数量。我希望将索引添加到列表中。

在Haskell中,我可以执行以下操作:

pre > zip [1 ..]abcdefghijklmnop
[(1,'a'),(2,'b'),(3,'c'),(4,'d '),(5,' E '),(6,' F '),(7,' G '),(8,' H '),(9,' I '),(10,' J') (11,'k'),(12,'1'),(13,'m'),(14,'n'),(15,'o'),(16,'p')] b $ b

现在想象一下字符串的大小是未知的。这仍然可以在Haskell中工作,并且整数列表根据需要给出尽可能多的整数,直到字符串用完。



我如何做Python中的等价物?



我试过这个:

  s =abcdefghijklmnop
indexedlist = []
for i,c in enumerate(s):
indexedlist .append((i,c))

>>> (5,'e'),(4,'e'),(5'''),(1,'b'), (6,'g'),(7,'h'),(8,'i'),(9,'j'),(10,'k'),(11,'1' ),(12,'m'),(13,'n'),(14,'o'),(15,'p')]

它可以工作,但我想知道是否有更简洁的方法,因为它是4行代码,感觉很好。

解决方案

只要执行 list(enumerate(s))即可。它遍历枚举对象并将其转换为 list


I have a list of elements in python. I don't know the number of elements in the list. I would like to add indexes to the list.

In Haskell, I could do the following

zip [1..] "abcdefghijklmnop"
[(1,'a'),(2,'b'),(3,'c'),(4,'d'),(5,'e'),(6,'f'),(7,'g'),(8,'h'),(9,'i'),(10,'j'),(11,'k'),(12,'l'),(13,'m'),(14,'n'),(15,'o'),(16,'p')]

Now imagine that the string was of unknown size. This would still work in Haskell, and the integer list gives as many integers as necessary until the string runs out.

How would one do the equivalent in Python?

I have tried this:

s = "abcdefghijklmnop"
indexedlist = []
for i,c in enumerate(s):
    indexedlist.append((i,c))

>>> indexedlist
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j'), (10, 'k'), (11, 'l'), (12, 'm'), (13, 'n'), (14, 'o'), (15, 'p')]

And it works, but I'm wondering if there is a shorter/cleaner way, since it is 4 lines of code and feels much.

解决方案

Just do list(enumerate(s)). This iterates over the enumerate object and converts it to a list.

这篇关于Python相当于Haskell的[1 ..](用于索引列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆