【问题标题】:Pick Index of Array and group to new array by Index of Array选择数组索引并按数组索引分组到新数组
【发布时间】:2019-08-10 10:25:53
【问题描述】:

我有一个数组,每个索引将跟随另一个索引,并且索引不会跟随相同的索引。在该索引为当前索引之后,索引将跟随索引为目标

这是python的代码

list_value = [1,2,3]
for current in range(len(list_value)):
   for target in range(len(list_value)):

     if current == target: continue
     list_target.append(target)

预期输出为{current:0, target:[1,2,0,2,0,1]}

但我需要的结果是

{current:0, target:[1,2]}
{current:1, target:[0,2]}
{current:2, target:[0,1]}

我只添加新目标并重复直到 list_value 的长度完成,我需要帮助,请

非常感谢

【问题讨论】:

    标签: arrays python-3.x sorting dictionary indexing


    【解决方案1】:

    如果我正确理解您的问题,我相信您想要做的是:

    list_value = [1, 2, 3]
    for current in range(len(list_value)):
        result = {"current": current, "target": []}
        for target in range(len(list_value)):
            if current != target:
                result["target"].append(target)
        print(result) # do something with each result here
    

    这应该打印出来

    {'current': 0, 'target': [1, 2]}
    {'current': 1, 'target': [0, 2]}
    {'current': 2, 'target': [0, 1]}
    

    【讨论】:

    • @Subhanshuja 如果这可行,您可以 +1 并接受它作为答案吗
    • 接受,我还是 stackoverflow 的新手,我无法添加 +1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    相关资源
    最近更新 更多