duanjianshen4871 2018-04-05 04:04 采纳率: 100%
浏览 108

如何从多维数组中替换重复值?

I have an array like this:

[0] => array([location] => [10.1111111,106.2222222];);

[1] => array([location] => [10.1111111,106.2222222];)

[2] => array([location] => [10.3333333,106.444444444];)

[3] => array([location] => [10.1111111,106.2222222];)

[4] => array([location] => [10.3333333,106.444444444];)

I want to keep first array value ( of duplicate values) , and replace all the duplicate value remaining with random number

[0] => array([location] => [10.1111111,106.2222222];)

[1] => array([location] => [10.54545422,106.136633434];)

[2] => array([location] => [10.3333333,106.444444444];)

[3] => array([location] => [10.323123232,106.656565654];)

[4] => array([location] => [10.44342266,106.87878787];)

my code but it's not seem to work:

foreach($dataMap as $items) {

            $temp = array();
            foreach($items as $value) {

                if(!isset($temp[$value])) {
                    $temp[$value] = '[10.888888,106.999999]';
                }
            }
            $items['location'] = $temp;
        }
  • 写回答

2条回答 默认 最新

  • duankuaiwang2706 2018-04-05 04:26
    关注

    Usually I create a list or set and validate each value to that list, if exist then replace the decimal values and add to the list or set else add the value, by this we achieve unique values.

    This is how I do it in python.

    import random
    
    arr = list()
    arr.append([10.1111111, 106.2222222])
    arr.append([10.1111111, 106.2222222])
    arr.append([10.3333333,106.444444444])
    arr.append([10.1111111, 106.2222222])
    
    print(arr)
    
    # Set to check duplicates..
    dup = set()
    temp_arr = list()
    
    for each_row in range(len(arr)):
        temp_arr.append([])
        for each_col in range(len(arr[each_row])):
            val = arr[each_row][each_col]
            if val in dup:  # found duplicate
                my_int = int(val)
                # new value
                new_val = round(random.uniform(my_int, my_int+1), 7)
                temp_arr[each_row].append(new_val)
                dup.add(new_val)
            else:
                dup.add(val)  # non duplicates.
                temp_arr[each_row].append(val)
    print(temp_arr)
    
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改