我有一个元组元组列表:
/* Tests and Examples */
let arr1d : [Double] = [3.0, 4.0, 0.0]
let arr2d : [Double] = [-3.0, -4.0, 0.0]
let arr3d : [Double] = [-3.0, -4.0]
let arr1f : [Float] = [-3.0, -4.0, 0.0]
let arr1i = [1, 2, 3]
let _a = arr1d.dimension() // 3, OK
let _b = arr1d.distance(arr2d) // 10, OK (A->B dist)
let _c = arr1d.distance(arr1f) // nil (Incomp. types)
let _d = arr1d.distance(arr3d) // nil (Incomp. sizes)
let _e = arr1i.distance(arr1d) // nil (Incomp. types)
/* for use in function calls: generic array parameters constrained to
those that conform to protocol 'EuclidianPoint', as requested */
func bar<T: MyTypes, U: protocol<EuclideanPoint, _ArrayType> where U.Generator.Element == T> (arr1: U, _ arr2: U) -> Double? {
// ...
return arr1.distance(Array(arr2))
/* We'll need to explicitly tell the distance function
here that we're sending an array, by initializing an
array using the Array(..) initializer */
}
let myDist = bar(arr1d, arr2d) // 10, OK
我正在尝试返回与特定字符串匹配的所有项目。到目前为止,我有这个:
countries = [(('germany', 'berlin'),3),(('england', 'london'),90),(('holland', 'amsterdam'), 43)]
返回:
for i in countries:
if i[0] == 'germany':
print i
我想要的输出是:
('germany', 'berlin')
我已经查看了文档中的列表理解,但我无法弄清楚如何显示每个元组的数字。
答案 0 :(得分:2)
您正在寻找的代码是
for i in countries:
if i[0][0] == 'germany':
print i
由于您对索引感到有点困惑:
i --> (('germany', 'berlin'),3)
i[0] --> ('germany,'berlin')
i[0][0] --> 'germany'
答案 1 :(得分:2)
如果您自己构建该数据结构,我建议您使用更明确的结构,如dict或namedtuple。
根据您的数据结构,您需要的是:
countries = [(('germany', 'berlin'),3),(('england', 'london'),90),(('holland', 'amsterdam'), 43)]
for country in countries:
if country[0][0]:
print(country)
有了词典,你可以:
countries = [{'id': 3,
'info': {'name': 'germany',
'capital': 'berlin'}},
{'id': 90,
'info': {'name': 'england',
'capital': london}}]
for country in countries:
if country['info']['name'] == 'germany':
print(country)
我个人认为这更容易阅读。在这种情况下,namedtuple可能是一个更好的结构,但它稍微复杂一些。
答案 2 :(得分:1)
目前的答案已经足够,但是如果你想检查元组中的两个项目,你可以这样做:
for i in countries:
if 'germany' in i[0]:
print i