具体的Python反向函数问题

时间:2016-05-18 22:46:48

标签: python

def flip_keys(to_flip):  
    """To reverse items in a mixed list

    Args:
        to_flip(list): a list mixed with tuple and other values.

    Returns:
        list: to return values in the list, reversed.

    Examples:

        >>> flip_keys([(1, 2, 3), 'abc'])
        '[(3, 2, 1), 'cba']
    """
    counter = 0
    for value in to_flip:
        to_flip[counter] = value[::-1]
        counter += 1
    return to_flip

这是一个python函数,它是向后翻转输入的每个元素。我学会了索引,但to_flip [counter]就像我看到的一样。在翻转每个元素时,to_flip [counter]的用途是什么?它有名字吗?并没有反作用来添加给出的每个数字,并得出一笔金额?为什么需要这里?对于初学者来说,有没有其他方法可以像这样做反向。谢谢。

1 个答案:

答案 0 :(得分:1)

to_flip行正在翻转该元素中的任何内容。例如,如果您只在一个列表上运行它:

my_list = [1,2,3,4,5]
flipped_list = my_list[::-1]

flipped_list现在为[5,4,3,2,1][::-1]是翻转任何列表的简洁简写。

对于您的代码,counter会跟踪to_flip中您所在的元素。您也可以使用enumerate跟踪列表中的for i, value in enumerate(to_flip): to_flip[i] = value[::-1] ,它也会计算您所在的元素:

Direction // x and y tuple/variable, integer, or string

Point // x and y tuple/variable. Note that you can use this as direction too 

Vertex
- Point
- Map < Direction, Edge > // each direction is linked to another vertex
                          // maps in C can be made with two arrays
                          // a vertex for each direction may be easier

Edge
- Vertex // you can store both vertices, but you only need to store the one being moved to. 
         // without OOP, reuse a simple struct before making it complex

Graph
- Vertices // array of vertex
           // each vertex stores its edges; the graph doesn't need to