• ## tuples

2014-08-09 19:12:11
A tuple is an immutable list. A tuple can not be changed in any way once it is created. Example 3.15. Defining a tuple ...>>> t = ("a", "b", "mpilgrim", "z", "example") ...('a', 'b', 'mpilg

A tuple is an immutable list. A tuple can not be changed in any way once it is created.

Example 3.15. Defining a tuple
>>> t = ("a", "b", "mpilgrim", "z", "example") >>> t
('a', 'b', 'mpilgrim', 'z', 'example')
>>> t[0]                                       'a'
>>> t[-1]                                      'example'
>>> t[1:3]                                     ('b', 'mpilgrim')

A tuple is defined in the same way as a list, except that the whole set of elements is enclosed in parentheses instead of square brackets.

The elements of a tuple have a defined order, just like a list. Tuples indices are zero-based, just like a list, so the first element of a non-empty tuple is always t[0].

Negative indices count from the end of the tuple, just as with a list.

Slicing works too, just like a list. Note that when you slice a list, you get a new list; when you slice a tuple, you get a new tuple.

Example 3.16. Tuples Have No Methods
>>> t
('a', 'b', 'mpilgrim', 'z', 'example')
>>> t.append("new")    Traceback (innermost last):
File "<interactive input>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'append'
>>> t.remove("z")      Traceback (innermost last):
File "<interactive input>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'remove'
>>> t.index("example") Traceback (innermost last):
File "<interactive input>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'index'
>>> "z" in t           True

You can't add elements to a tuple. Tuples have no append or extend method.

You can't remove elements from a tuple. Tuples have no remove or pop method.

You can't find elements in a tuple. Tuples have no index method.

You can, however, use in to see if an element exists in the tuple.

So what are tuples good for?

Tuples are faster than lists. If you're defining a constant set of values and all you're ever going to do with it is iterate through it, use a tuple instead of a list.It makes your code safer if you “write-protect” data that does not need to be changed. Using a tuple instead of a list is like having an implied assert statement that shows this data is constant, and that
special thought (and a specific function) is required to override that.Remember that I said that dictionary keys can be integers, strings, and “a
few other types”? Tuples are one of those types. Tuples can be used as keys in a dictionary, but lists can't be used this way.Actually, it's more complicated than that. Dictionary keys must be immutable. Tuples themselves are immutable, but if you have
a tuple of lists, that counts as mutable and isn't safe to use as a dictionary key. Only tuples of strings, numbers, or other dictionary-safe tuples can be used as dictionary keys.Tuples are used in string formatting, as you'll see shortly.

Tuples can be converted into lists, and vice-versa. The built-in tuple function takes a list and returns a tuple with the same elements, and the list function
takes a tuple and returns a list. In effect, tuple freezes a list, and list thaws a tuple.

展开全文
• This conflicts with the spec, which allows for partial (or even empty) tuples to pass validation unless 'minItems' is also set. <p>See the relevant section of ...
• <div><p>Arbitrary is implemented for n-tuples up to n=12. For completeness this also includes 1-tuples, which were missing before. This is achieved by refactoring the shrink implementations for an...
• <div><p>This change adds lightweight generic typed tuples as subclasses of <code>RACTuple</code>. This allows tuples to be annotated with the types that they contain, e.g. <code>RACTwoTuple<...
• <p>Adds support for tuples by modifying low-level utility functions used for ABI dict processing and encodability checks. <h4>Cute Animal Picture <p><img alt="Put a link to a cute animal picture ...
• distributed.utils - ERROR - addresses should be strings or tuples, got None Traceback (most recent call last): File "C:\ProgramData\Anaconda3\envs\fiction\lib\site-packages\distributed\utils.py&#...
• <div><p>Hey, suggestion to improve the API of <code>EVReflection</code>: User named arguments for tuples. <p><strong>Example:</strong></p> <pre><code>swift open func propertyConverters() -> [...
• <div><p>It would be helpful if Tuples implemented element accessor interfaces. <pre><code> java public interface V1<t1>{ T1 v1(); } public interface V2<t2>{ T2 v2(); } public interface ...
• <div><p>Currently, the macro push type tuples to the end of generics. <p>Say we have a <code>Foo<X, Y></code> struct, the signature of generated <code>FooBuilder</code> is <code>FooBuilder<X,...
• <div><p>I replaced tuples in domain models with domain types, because tuples are names not included in a ubiquitous language. <p>In my opinion, tuples should only be used as a business workflow output...
• <div><p>This makes msgpack decode arrays as tuples rather than lists, allowing them to be used within containers like set and dict that expect hashable elements. <p>cc <p>I took a quick look at this ...
• <div><p>该提问来源于开源项目：ramda/ramda-fantasy</p></div>
• <p>Without this PR, inserting tuples with SELECT may insert more tuples than required, e.g. <code>INSERT INTO foo1 SELECT a, b FROM foo1;</code> will insert more than the number of tuples already ...
• A simple alternative would be to have <code>__getitem__</code> support tuples such as (l,b,r,t)</code>. <p>In general, the tuple would be twice the length of the number of applicable key dimensions ...
• <div><p>Mutating values that are referenced by tuples can lead to all sorts of problems (e.g., the state of the database can be inconsistent with the key constraints; derivations can exist that don&#...
• <div><p>There are three archetypal forms in computer languages: scalars, lists/tuples/arrays, and maps. <p>RPM macros only implement scalar key:value assignments. This RFE is a suggested extension to ...
• Instead of generating Tuples, it generates vertices as Lists: <p><img alt="immagine" src="https://user-images.githubusercontent.com/6708848/48337715-fd435800-e663-11e8-9678-20df6e9b1ace.png" /></p> ...
• <code>Error: filtering with tuples or arrays not supported (argument="contract.docHash", value=[], code=INVALID_ARGUMENT, version=abi/5.0.1)</code></p> <p>Is it possible to ...
• <div><p>Is there a way to create a tuple of tuples? Example: (('user1', 'user1.com'), ('user2', 'user2.com'), ) <p>I have the same problem trying to create a list of ...
• According to the pystorm <a href="https://github.com/pystorm/pystorm/blob/master/doc/source/quickstart.rst#failed-tuples">quickstart docs</a> and numerous things I've read, calling <code>fail...
• ValueError: LineStrings must have at least 2 coordinate tuples" when I pass this: <p>splitted = shapely.ops.split(line, points) <p>...where line is a multilinestring object and points a ...
• Tuple is a collection of Python objects much like a list. The sequence of values stored in a tuple can be of any type, and they are indexed by integers. The important difference between a list and a ...
Tuple is a collection of Python objects much like a list. The sequence of values stored in a tuple can be of any type, and they are indexed by integers. The important difference between a list and a tuple is that tuples are immutable. Also, Tuples are hashable whereas lists are not.  tuple是一种数据类型，和list相似，元素可以是任何数据类型，下标是整数，list和tuple的差别是tuple的元素是不可修改的，tuple是hashable但是list不是。
Values of a tuple are syntactically separated by ‘commas’. Although it is not necessary, it is more common to define a tuple by closing the sequence of values in parentheses. This helps in understanding the Python tuples more easily.

Tuples are immutable, and usually, they contain a sequence of heterogeneous elements that are accessed via unpacking or indexing (or even by attribute in the case of named tuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list. tuple是不可变的，元素可以是不同种类的，list是可变的，元素通常是同种类的，使用迭代访问。

创建tuple

# Python program to demonstrate
# Addition of elements in a Set

# Creating an empty tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)

# Creating a Tuple with
# the use of Strings
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with
# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))

# Creating a Tuple
# with the use of loop
Tuple1 = ('Geeks')
n = 5
print("\nTuple with a loop")
for i in range(int(n)):
Tuple1 = (Tuple1,)
print(Tuple1)

# Creating a Tuple with the
# use of built-in function
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)

# Creating a Tuple with
# Mixed Datatypes
Tuple1 = (5, 'Welcome', 7, 'Geeks')
print("\nTuple with Mixed Datatypes: ")
print(Tuple1)

# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)

# Creating a Tuple
# with repetition
Tuple1 = ('Geeks',) * 3
print("\nTuple with repetition: ")
print(Tuple1) 

tuple的连接

Concatenation of tuple is the process of joining of two or more Tuples. Concatenation is done by the use of ‘+’ operator. Concatenation of tuples is done always from the end of the original tuple. Other arithmetic operations do not apply on Tuples.Note- Only same datatypes can be combined with concatenation, an error arises if a list and a tuple are combined.

concatenation是连接两个tuple的方法，使用+操作实现，其他算术操作不能用在tuple上，concatenation的使用必须是同类型的数据。

# Concatenaton of tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('Geeks', 'For', 'Geeks')

Tuple3 = Tuple1 + Tuple2

# Printing first Tuple
print("Tuple 1: ")
print(Tuple1)

# Printing Second Tuple
print("\nTuple2: ")
print(Tuple2)

# Printing Final Tuple
print("\nTuples after Concatenaton: ")
print(Tuple3) 

tuple的切片

Slicing of a Tuple is done to fetch a specific range or slice of sub-elements from a Tuple. Slicing can also be done to lists and arrays. Indexing in a list results to fetching a single element whereas Slicing allows to fetch a set of elements.Note- Negative Increment values can also be used to reverse the sequence of Tuples

切片用来获得tuple特定范围的元素，list和array可以用切片。下标可以获得单个元素，切片可以获得多个元素，负下标也可以在tuple上使用。

# Slicing of a Tuple

# Slicing of a Tuple
# with Numbers
Tuple1 = tuple('GEEKSFORGEEKS')

# Removing First element
print("Removal of First Element: ")
print(Tuple1[1:])

# Reversing the Tuple
print("\nTuple after sequence of Element is reversed: ")
print(Tuple1[::-1])

# Printing elements of a Range
print("\nPrinting elements between Range 4-9: ")
print(Tuple1[4:9]) 

Output:

Removal of First Element:
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')

Tuple after sequence of Element is reversed:
('S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G')

Printing elements between Range 4-9:
('S', 'F', 'O', 'R', 'G')

删除tuple，整个删除

# Deleting a Tuple

Tuple1 = (0, 1, 2, 3, 4)
del Tuple1

print(Tuple1) 

Traceback (most recent call last):
File “/home/efa50fd0709dec08434191f32275928a.py”, line 7, in
print(Tuple1)
NameError: name ‘Tuple1’ is not defined


展开全文
• <div><p>Allows <code>check_dimension</code> to handle tuples of numpy integers and floats. <p>In cases where a tuple passed to <code>check_dimension</code> contains numpy int and float types, the ...

Tuples

Tuples 可以用一对圆括号包裹若干个值，这些值的类型可以互不相同。

Tuples中可以包含任意类型

你可以像下面这样赋值
let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
// 输出 "The status code is 404"
print("The status message is \(statusMessage)")
如果只需要Tuples中部分值，其他不需要的值可以用 _ 代替
例如：
let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
// 输出 "The status code is 404"
你也可以通过下标来获取值，下标从0开始
例如：
print("The status code is \(http404Error.0)")
// 输出 "The status code is 404"
print("The status message is \(http404Error.1)")
你可以给Tuple中个元素取个名字
例如：
let http200Status = (statusCode: 200, description: "OK")
这样你就可以直接通过名字获取元素
print("The status code is \(http200Status.statusCode)")
// 输出 "The status code is 200"
print("The status message is \(http200Status.description)")
// 输出 "The status message is OK"
Tuples 可以作为函数的值返回


原文  Tuples https://developer.apple.com/library/prerelease/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309
展开全文
• <div><p>Spanner supports queries with lists of tuples: <code>SELECT * FROM Foo WHERE (a, b) IN (("x", 1), ("y", 2))</code>. The Spanner API library's Statement builder seems to not...
• The same could be done for tuples, and dicts. <p>It may be reasonably safe to extend this to subclasses of list, tuple and dicts too. This way it would work for nametuples, defaultdicts, etc... <ul>...
• <div><p>twine is going to start ...<p>And it should assert that the tuples provided are of length 2.</p><p>该提问来源于开源项目：requests/toolbelt</p></div>

...