从列表转换为字典 [英] Convert from list to dictionary

查看:85
本文介绍了从列表转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经得到它以当前格式生成邻接列表:

 carbongraph = {'(0,1)':[(0,2)],' (0,2)':[(0,1),(0,3),(1,2)],'(0,3)':[(0,2)],'(1,2)' :[(0,2),(2,2)],'(2,2)':[(1,2)]} 



但这种格式会不能用于我最长的路径算法,它会出现以下错误

 TypeError:类型为'NoneType'的对象没有len()



但由于某种原因它将以下列格式工作:

 carbongraph = {'(0,1)':['(0,2)' ],'(0,2)':['(0,1)','(0,3)','(1,2)'],
'(0,3)':[' (0,2)'],'(1,2)':['(0,2)','(2,2)'],'(2,2)':['(1,2)' ]}



那么我如何从当前格式转换为所需格式



什么我试过了:



 grid = [[0,1,1,1],
[0, 0,1,0],
[0,0,1,0]]

lst = []
行,排成行枚举(网格):
表示cols,col表示枚举(行):
if grid [rows] [cols] in [1]:
lst.append((rows,cols))


print(lst)


adjacencylist = []

def adjacentnode(nodea,nodeb):
如果nodea [0] == nodeb [0]和nodea [1] == nodeb [1] + 1:
adjacent = True
elif nodea [0] == nodeb [0]和nodea [1] == nodeb [1] -1:
adjacent = True
elif nodea [1] == nodeb [1]和nodea [0] == nodeb [0] +1:
adjacent = True
elif nodea [1] == nodeb [1]和nodea [0] == nodeb [0] -1:
adjacent = True
else:
adjacent = False
返回邻近

#Below是转换发生的地方
carbongraph = {}
范围内的节点(len(lst)):
adjacencylist.append((lst [node],[]))
表示邻居的范围(len(lst)):
adjacentnodes =(adjacentnode(lst [node],lst [neighbor]) )

if adjacentnodes == True:
adjacencylist [node] [1] .append(lst [neighbor])

for adjacencylist中的item:
carbongraph [str(item [0] )] =(item [(1)])
for item in item [1]:
adj = str(adj)

def shortestpath(graph,start,end, path = []):
path = path + [start]
if start == end:
return path
if start not in graph:
return None
表示节点[start]:
如果节点不在路径中:
newpath = shortestpath(graph,node,end,path)
if newpath:
return newpath
返回无

LeafArray = []
for carbongraph:
degree =(len(carbongraph [leaf]))
if degree == 1:

LeafArray.append(leaf)
print(LeafArray)

chainlist = []
for LeafArray中的节点:$ b​​ $ b for LeafArray中的邻居:
currentpath =(shortestpath(carbongraph,node,neighbor))
c arbonchain = len(currentpath)#error发生在这里
print(currentpath)
chainlist.append(carbonchain)

longestchain = max(chainlist)
print(longestchain)

def Prfix():
如果longestchain == 4:
prefix =但是
elif longestchain == 5:
prefix =Pent
elif longestchain == 6:
prefix =Hex
elif longestchain == 7:
prefix =Hept
elif longestchain == 8:
prefix =Oct
返回前缀

print(Prfix())

解决方案

< blockquote>您需要查看列表和列表推导以获取建议。请参见 5。数据结构 - Python 3.7.3文档 [ ^ ]。


看看这里:使用PHP和JavaScript数组/对象转换和循环JSON - Jonathan Suh [ ^ ]


引用:

从列表转换为字典



这里没有字典,你需要将字符串从给定格式转换为另一种格式。

我会使用RegEx,2次,以替换外部字符([]),并使用另一个元素。

引用:

这就是我需要完成的课程,请帮忙,

我们非常愿意帮助您,但不会为您做功课。你说的唯一问题就是你有功课。

HomeWork不会在乞求别人做你的工作时测试你的技能,它会让你思考并帮助你的老师检查您对所学课程的理解以及您应用这些课程时遇到的问题。

你的任何失败都会帮助你的老师发现你的弱点并设定补救措施。

你的任何失败都会帮助你了解什么有效,什么无效,被称为'试错'学习。

所以,试一试,重读课程并开始工作。如果您遇到特定问题,请展示您的代码并解释这个问题,我们可能会提供帮助。


I have got it to produce adjacency list in the current format:

carbongraph = {'(0, 1)': [(0, 2)], '(0, 2)': [(0, 1), (0, 3), (1, 2)], '(0, 3)': [(0, 2)], '(1, 2)': [(0, 2), (2, 2)], '(2, 2)': [(1, 2)]}


But this format will not work for my longest path algorithm, It gives the following error

TypeError: object of type 'NoneType' has no len()


but it will work in the following format for some reason:

 carbongraph = {'(0, 1)':['(0, 2)'], '(0, 2)':['(0, 1)','(0, 3)','(1, 2)'],
'(0, 3)':['(0, 2)'], '(1, 2)' :['(0, 2)','(2, 2)'], '(2, 2)':['(1, 2)']}


So how do i convert from the current format to the required format

What I have tried:

grid = [[0,1,1,1],
        [0,0,1,0],
        [0,0,1,0]]
        
lst = []
for rows, row in enumerate(grid) :
    for cols, col in enumerate(row) :
        if grid[rows][cols] in [1] :
            lst.append((rows, cols))
            
       
print (lst)
        

adjacencylist = []

def adjacentnode(nodea,nodeb):
    if nodea[0] == nodeb[0] and nodea[1] == nodeb[1] + 1:
        adjacent = True
    elif nodea[0] == nodeb[0] and nodea[1] == nodeb[1]-1:
        adjacent = True
    elif nodea[1] == nodeb[1] and nodea[0] == nodeb[0]+1:
        adjacent = True
    elif nodea[1] == nodeb[1] and nodea[0] == nodeb[0]-1:
        adjacent = True
    else:
        adjacent = False
    return adjacent

#Below is where conversion happens
carbongraph = {}
for node in range(len(lst)):
    adjacencylist.append((lst[node],[]))
    for neighbour in range(len(lst)):
        adjacentnodes = (adjacentnode(lst[node],lst[neighbour]))
        
        if adjacentnodes == True:
            adjacencylist[node][1].append(lst[neighbour])
        
for item in adjacencylist:
    carbongraph[str(item[0])] = (item[(1)])
    for adj in item[1]:
        adj = str(adj)
    
def shortestpath(graph, start, end, path = []):
  path = path + [start]
  if start == end:
      return path
  if start not in graph:
      return None
  for node in graph[start]:
      if node not in path:
          newpath = shortestpath(graph, node, end, path)
          if newpath: 
            return newpath
  return None

LeafArray = []
for leaf in carbongraph:
  degree = (len(carbongraph[leaf]))
  if degree == 1:
    
    LeafArray.append(leaf)
print(LeafArray)

chainlist = []
for node in LeafArray:
    for neighbour in LeafArray:
      currentpath = (shortestpath(carbongraph,node,neighbour))
      carbonchain = len(currentpath)#error occurs here
      print (currentpath)
      chainlist.append(carbonchain)
      
longestchain = max(chainlist)
print (longestchain)

def Prfix():
  if longestchain == 4:
    prefix = "But"
  elif longestchain == 5:
    prefix = "Pent"
  elif longestchain == 6:
    prefix = "Hex"
  elif longestchain == 7:
    prefix = "Hept"
  elif longestchain == 8:
    prefix = "Oct"
  return prefix

print (Prfix())

解决方案

You need to look at lists and list comprehensions for suggestions. See 5. Data Structures — Python 3.7.3 documentation[^].


Take a look here: Convert and Loop through JSON with PHP and JavaScript Arrays/Objects — Jonathan Suh[^]


Quote:

Convert from list to dictionary


There is no dictionary here, you need to convert a string from given format to another format.
I would use RegEx, 2 times, on to replace the external chars ("[]"), and another for each elements.

Quote:

This is all i need to complete my coursework, please help,


We are more than willing to help you, but not doing your homework for you. And the only problem you stated is that you have homework.
HomeWork is not set to test your skills at begging other people to do your work, it is set to make you think and to help your teacher to check your understanding of the courses you have taken and also the problems you have at applying them.
Any failure of you will help your teacher spot your weaknesses and set remedial actions.
Any failure of you will help you to learn what works and what don't, it is called 'trial and error' learning.
So, give it a try, reread your lessons and start working. If you are stuck on a specific problem, show your code and explain this exact problem, we might help.


这篇关于从列表转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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