python-List-tuples-Dictionary usage detailed

Source: Internet
Author: User

List

Format: name = []

name = [Name1, name2, Name3, Name4, Name5]

#针对列表的操作

Name.index ("name1") #查询指定数值的下标值
Name.count ("name1") #查询指定数值的总数
Name.clear ("name") #清空列表
Name.reverse ("name") #反转列表数值
Name.sort ("name") #排序, precedence special characters-digits-uppercase letters-lowercase letters
Name.extend ("name1") #扩展. Add the value of another list to the current list
#增加 add

Name.append ("Name5") #追加
Name.insert (1, "name1.5") #插入指定位置
#删除 Delete

Name.remove ("name1") #根据人名删除
Del Name[0] #根据下标删除列表里的值
del name #删除列表
Name.pop (0) #删除指定下标的值, the default is the last
#查询 Select

Print (Name[0], name[2]) #根据下标读取
Print (name[0:2]) = = Print (Name[:2]) #切片 (consecutive paragraph: Gu Tou regardless of the tail, 0 and 1 can be omitted)
Print (name[-1]) #-1 Gets the value of the last position
Print (name[-2:]) #获取最后两个值, from the last number is 1, 3,-2, 1
#更改 Update

NAME[1] = "name1.5" #更改指定下标的值
#列表copy分为深copy和浅copy

Deep copy will copy the list of the lists to the past

name = ["Name1", "name2", "Name3", "Name4", ["Name5", "Name6"]]
name1 = copy.deepcopy (name)
NAME[4][1] = "Name7"
NAME[1] = "name2.1"
Print (name)
Print (NAME1)
Result (results)

[' name1 ', ' name2.1 ', ' name3 ', ' name4 ', [' name5 ', ' Name7 ']]
[' name1 ', ' name2 ', ' name3 ', ' name4 ', [' name5 ', ' Name6 ']]
Light copy will only copy the first layer of the list, and if the values in the new file's subdatasheet change, the value of the old file's child list will not change

name = ["Name1", "name2", "Name3", "Name4", ["Name5", "Name6"]]
name1 = name.copy () = copy.copy (name) = name[:] = list (name)
NAME[4][1] = "Name7"
NAME[1] = "name2.1"
Print (name)
Print (NAME1)
Result (results)

[' name1 ', ' name2.1 ', ' name3 ', ' name4 ', [' name5 ', ' Name7 ']]
[' name1 ', ' name2 ', ' name3 ', ' name4 ', [' name5 ', ' Name7 ']

Tuples (immutable list)

Format: tuple = ("Tu1", "TU2")

As with the list, do not add to the deletion. Query only (slices)

Tuple = ("Tup1", "tup2")
Print (Tuple.count ("Tup1"))
Print (Tuple.index ("tup2"))
Exercises:

Program: Shopping Cart Program

Demand:

After starting the program, let the user enter the payroll, and then print the list of items
Allow users to purchase items based on the item number
After the user selects the product, checks whether the balance is enough, is enough directly to deduct the paragraph, is not enough to remind
Can exit at any time, print purchased goods and balances when exiting

#购物车练习题

Shoplist = [1, iphone, 6000], [2, Mac Pro, 12000], [3, "ipad Air", 8000], [4, "Chicken", 5], [5, "eggs", +], [6, "Bi" Ke ", 500]]
Mall = []
salary = Int (input ("Please input your Salary:"))
While True:
For I in range (0, Len (shoplist)):
Print (Shoplist[i])
Goodid = Int ("Please enter the number for want to buy Goods:")-1
if Int (shoplist[goodid][2]) > Salary:
Print ("Don ' t buy goods for you want")
Else
Mall.append (Shoplist[goodid])
Salary = salary-shoplist[goodid][2]
Yesorno = input ("To continue shopping?") Input Y or N ")
if Yesorno = = ' N ':
Print ("Do you have bought the goods:%s,remaining sum:%s"% (mall, salary))
Print ("for coming.")


Exercises

string/tuple/list/dictionary interchange

#-*-coding:utf-8-*-

#1, Dictionary
Dict = {' name ': ' Zara ', ' age ': 7, ' class ': ' A '

#字典转为字符串, return: <type ' str ' > {' age ': 7, ' name ': ' Zara ', ' class ': ' The '
Print type (str (dict)), str (DICT)

#字典可以转为元组, return: (' age ', ' name ', ' class ')
Print tuple (dict)
#字典可以转为元组, Back: (7, ' Zara ', ' ' a ')
Print tuple (dict.values ())

#字典转为列表, return: [' age ', ' name ', ' class ']
Print List (dict)
#字典转为列表
Print Dict.values

#2, META Group
tup= (1, 2, 3, 4, 5)

#元组转为字符串, Back: (1, 2, 3, 4, 5)
Print tup.__str__ ()

#元组转为列表, back: [1, 2, 3, 4, 5]
Print List (TUP)

#元组不可以转为字典

#3, List
Nums=[1, 3, 5, 7, 8, 13, 20];

#列表转为字符串, back: [1, 3, 5, 7, 8, 13, 20]
Print str (nums)

#列表转为元组, Back: (1, 3, 5, 7, 8, 13, 20)
Print tuple (nums)

#列表不可以转为字典

#4, String

#字符串转为元组, Back: (1, 2, 3)
Print tuple (eval (1,2,3))
#字符串转为列表, back: [1, 2, 3]
Print List (eval (1,2,3))
#字符串转为字典, back: <type ' dict ' >
Print type (eval (' {' name ': ' Ljq ', ' Age ': 24} '))

Tuples, lists, dictionaries of the differences.


1. List
A list is a data structure that handles a set of ordered items, that is, you can store a sequence of items in a list. The items in the list. The items in the list should be included in square brackets so that Python knows that you are specifying a list. Once you create a list, you can add, delete, or search the list of items. Since you can add or delete items, we say that the list is a mutable data type, that this type can be changed, and that the list can be nested.
Instance:
#coding =utf-8
animalslist=[' Fox ', ' Tiger ', ' rabbit ', ' snake '
print "I don ' t like these", Len (animalslist), ' animals ... '

For items in Animalslist:
Print items,

print "\ n after Operation"
#对列表的操作, add, delete, sort
Animalslist.append (' pig ')
Del Animalslist[0]
Animalslist.sort ()
For I in range (0,len (animalslist)):
Print Animalslist[i],
Results:
I don ' t like these 4 animals ...
Fox Tiger Rabbit Snake
After operation
Pig Rabbit Snake Tiger
2. META Group
Ganso and lists are very similar, but tuples are immutable. That is, you cannot modify tuples. Tuples are defined as a comma-delimited list of items through parentheses. Tuples are often used when a statement or user-defined function is safe to adopt a set of values, that is, the value of the tuple being used does not change. Tuples can be nested.
>>> zoo= (' Wolf ', ' Elephant ', ' penguin ')
>>> zoo.count (' Penguin ')
1
>>> zoo.index (' Penguin ')
2
>>> zoo.append (' pig ')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Attributeerror: ' Tuple ' object has no attribute ' append '
>>> del Zoo[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ' Tuple ' object doesn ' t support item deletion
3 Dictionaries
The dictionary is similar to the Address book where you find the address and contact details by contact name, that is, we associate the key (first name) with the value (details). Note that the key must be unique, just as if two people happen to have the same name, you can't find the right information.
The key-value pairs are marked in this way in the dictionary: D = {key1:value1, key2:value2}. Note that their key/value pairs are separated by colons, and each pair is separated by commas, all of which are included in curly braces. Also, remember that the key/value pairs in the dictionary are not in order. If you want a specific order, then you should sort them yourself before using them.
Instance:
#coding =utf-8
Dict1={' Zhang ': ' Zhang Jiahui ', ' Wang ': ' Wangbaoqiang ', ' li ': ' Bing bingbing ', ' Zhao ': ' Zhao Wei '}
#字典的操作, add, delete, print
dict1[' Huang ']= ' Huang Jiaju '
Del dict1[' Zhao ']
For Firstname,name in Dict1.items ():
Print Firstname,name
Results:
Li Bingbing
Wang Wangbaoqiang
Huang Huang Jiaju
Zhang Zhang Jiahui

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.