Iterate over pairs in a list (circular fashion) in Python

前端 未结 13 1914
醉酒成梦
醉酒成梦 2020-12-01 01:14

The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).

I\'ve thought about two unpyth

13条回答
  •  失恋的感觉
    2020-12-01 02:12

    def pairs(ex_list):
        for i, v in enumerate(ex_list):
            if i < len(list) - 1:
                print v, ex_list[i+1]
            else:
                print v, ex_list[0]
    

    Enumerate returns a tuple with the index number and the value. I print the value and the following element of the list ex_list[i+1]. The if i < len(list) - 1 means if v is not the last member of the list. If it is: print v and the first element of the list print v, ex_list[0].

    Edit:

    You can make it return a list. Just append the printed tuples to a list and return it.

    def pairs(ex_list):
        result = []
        for i, v in enumerate(ex_list):
            if i < len(list) - 1:
                result.append((v, ex_list[i+1]))
            else:
                result.append((v, ex_list[0]))
        return result
    

提交回复
热议问题