我有两个功能。他们实际上在做同样的事情。通过fieldNameArray从数据库结果中获取数据到Int或Double数组中。如何将这两个函数合并为一个?那可能吗 ?唯一的区别是字段类型,所以返回类型。
.b img{
display: block;
}
.wrapper{
min-height:200pt;
}
答案 0 :(得分:3)
您可以尝试泛型,例如
func fieldsToNumber<T> ( fieldNameArray : [String] ) -> [T] {
var returnArray = [T]()
for fNA in fieldNameArray {
let n = T ( results.int(forColumn: fNA) )
returnArray.append( n )
}
return returnArray;
}
答案 1 :(得分:3)
是的,有可能应该使用Generics,尤其是您需要通用函数。
解决您问题的代码大致如下:
#!/usr/bin/env python
"""
Given a list of triangles, find the connected components.
https://stackoverflow.com/q/61584283/2912349
"""
import itertools
import networkx as nx
faces = [[ 2, 1, 0], [ 0, 3, 2], [ 1, 4, 0], [ 0, 4, 3], [ 5, 1, 2], [ 3, 5, 2],
[ 5, 4, 1], [ 4, 5, 3], [ 8, 7, 6], [ 6, 9, 8], [ 7, 10, 6], [ 6, 10, 9],
[11, 7, 8], [ 9, 11, 8], [11, 10, 7], [10, 11, 9]]
#create graph
edges = []
for face in faces:
edges.extend(list(itertools.combinations(face, 2)))
g = nx.from_edgelist(edges)
# compute connected components and print results
components = list(nx.algorithms.components.connected_components(g))
for component in components:
print(component)
# {0, 1, 2, 3, 4, 5}
# {6, 7, 8, 9, 10, 11}
# separate faces by component
component_to_faces = dict()
for component in components:
component_to_faces[tuple(component)] = [face for face in faces if set(face) <= component] # <= operator tests for subset relation
for component, component_faces in component_to_faces.items():
print(component, component_faces)
# (0, 1, 2, 3, 4, 5) [[2, 1, 0], [0, 3, 2], [1, 4, 0], [0, 4, 3], [5, 1, 2], [3, 5, 2], [5, 4, 1], [4, 5, 3]]
# (6, 7, 8, 9, 10, 11) [[8, 7, 6], [6, 9, 8], [7, 10, 6], [6, 10, 9], [11, 7, 8], [9, 11, 8], [11, 10, 7], [10, 11, 9]]
请用函数// This is a struct to mock the code you didn't post
struct Results {
func int(forColumn: String) -> Int16 {
return 1
}
}
let results = Results()
protocol DatabaseElementRepresentable {
init?(_ databaseValue: Int16)
}
func fields<Element: DatabaseElementRepresentable>(fieldNameArray : [String]) -> [Element] {
var returnArray = [Element]()
for fNA in fieldNameArray {
if let n = Element(results.int(forColumn: fNA)) {
returnArray.append(n)
}
}
return returnArray
}
extension Int: DatabaseElementRepresentable { }
extension Double: DatabaseElementRepresentable { }
let ints: [Int] = fields(fieldNameArray: ["test"])
let doubles: [Double] = fields(fieldNameArray: ["test"])
返回的值更改Int16