将多个元组添加到列表中

时间:2017-12-29 17:08:56

标签: python

我想添加所有行的坐标,如下所示

coordinates = []    
for line in lines:
        for x1,y1,x2,y2 in line:
            coordinates.extend((x1,y1),(x2,y2))

稍后检索x和y坐标以进行进一步计算

x,y = zip(*coordinates)

我得到错误TypeError:extend()只接受一个参数(给定2个)。如何在不调用extend两次的情况下实现上述目标

coordinates.extend((x1,y1))  
coordinates.extend((x2,y2))   

4 个答案:

答案 0 :(得分:2)

元素应该在元组或列表中

coordinates.extend(((x1, y1), (x2, y2)))

实现的行为
coordinates.extend((x1, y1))
coordinates.extend((x2, y2))

可以用

实现
coordinates.extend((x1, y1, x2, y2))

答案 1 :(得分:2)

extension URLRequest { /// Populate the HTTPBody of `application/x-www-form-urlencoded` request /// /// - parameter parameters: A dictionary of keys and values to be added to the request mutating func setBodyContent(_ parameters: [String : String]) { let parameterArray = parameters.map { (key, value) -> String in let encodedKey = key.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)! let encodedValue = value.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)! return "\(encodedKey)=\(encodedValue)" } httpBody = parameterArray .joined(separator: "&") .data(using: .utf8) } } extension CharacterSet { /// Character set containing characters allowed in query value as outlined in RFC 3986. /// /// RFC 3986 states that the following characters are "reserved" characters. /// /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" /// /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" /// should be percent-escaped in the query string. /// /// - parameter string: The string to be percent-escaped. /// /// - returns: The percent-escaped string. static var urlQueryValueAllowed: CharacterSet = { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" var allowed = CharacterSet.urlQueryAllowed allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode) return allowed }() }

或者你可以把整个事情放在列表理解中:

coardinates.extend([(x1,y1),(x2,y2)])

答案 2 :(得分:2)

使用list inside extend extend迭代列表并附加其中的所有元素。

coordinates.extend([(x1, y1), (x2, y2)])

  

co = []

     

co.extend([(1,2),(3,4)])

     

     

[(1,2),(3,4)]

答案 3 :(得分:0)

您可以将整个过程包含在一个理解中:

coordinates =  [p for l in lines for p in map(tuple, (l[:2], l[2:]))]

或者如果这些行本身不是元组:

{{1}}