Core Python

Tuples
A tuple is a sequence of arbitrary objects separated by commas and enclosed in parentheses. If the tuple contains a single object, the parentheses may be omitted. Tuples support the same operations as strings; they are also immutable.

>>> rec = (’Smith’,’John’,(6,23,68)) # This is a tuple
>>> lastName,firstName,birthdate = rec # Unpacking the tuple
>>> print firstName
John
>>> birthYear = birthdate[2]
>>> print birthYear
68
>>> name = rec[1] + ’ ’ + rec[0]
>>> print name
John Smith
>>> print rec[0:2]
(’Smith’, ’John’)

Lists
A list is similar to a tuple, but it is mutable, so that its elements and length can be changed.Alist is identified by enclosing it in brackets.Here is a sampling of operations that can be performed on lists:

>>> a = [1.0, 2.0, 3.0] # Create a list
>>> a.append(4.0) # Append 4.0 to list
>>> print a
[1.0, 2.0, 3.0, 4.0]
>>> a.insert(0,0.0) # Insert 0.0 in position 0
>>> print a
[0.0, 1.0, 2.0, 3.0, 4.0]
>>> print len(a) # Determine length of list
5
>>> a[2:4] = [1.0, 1.0] # Modify selected elements
>>> print a
[0.0, 1.0, 1.0, 1.0, 1.0, 4.0]

If a is a mutable object, such as a list, the assignment statementb = adoes not result in a new object b, but simply creates a new reference to a. Thus any changes made to b will be reflected in a. To create an independent copy of a list a, use the statement c = a[:], as illustrated below.

>>> a = [1.0, 2.0, 3.0]
>>> b = a # ’b’ is an alias of ’a’
>>> b[0] = 5.0 # Change ’b’
>>> print a
[5.0, 2.0, 3.0] # The change is reflected in ’a’
>>> c = a[:] # ’c’ is an independent copy of ’a’
>>> c[0] = 1.0 # Change ’c’
>>> print a
[5.0, 2.0, 3.0] # ’a’ is not affected by the change

Matrices can represented as nested lists with each row being an element of the list. Here is a 3 × 3 matrix a in the formof a list:

>>> a = [[1, 2, 3], \
[4, 5, 6], \
[7, 8, 9]]
>>> print a[1] # Print second row (element 1)
[4, 5, 6]
>>> print a[1][2] # Print third element of second row
6

Reading Input
A convenient way to input a number and assign it to the variable a is

a = eval(raw input(prompt))

Printing Output
The modulo operator (%) can be used to format a tuple. The formof the conversion statement is

%format1 %format2 · · ·’ % tuple
>>> a = 1234.56789
>>> n = 9876
>>> print ’%7.2f’ % a
1234.57
>>> print ’n = %6d’ % n # Pad with 2 spaces
n = 9876
>>> print ’n = %06d’ %n # Pad with 2 zeroes
n = 009876
>>> print ’%12.4e %6d’ % (a,n)
1.2346e+003 9876
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值