返回介绍

Lists, Tuples, Dictionaries

发布于 2025-02-25 23:43:35 字数 4263 浏览 0 评论 0 收藏 0

Lists

Lists are exactly as the name implies. They are lists of objects. The objects can be any data type (including lists), and it is allowed to mix data types. In this way they are much more flexible than arrays. It is possible to append, delete, insert and count elements and to sort, reverse, etc. the list.

a_list = [1,2,3,"this is a string",5.3]
b_list = ["A","B","F","G","d","x","c",a_list,3]
print(b_list)
print(b_list[7:9])
a = [1,2,3,4,5,6,7]
a.insert(0,0)
print(a)
a.append(8)
print(a)
a.reverse()
print(a)
a.sort()
print(a)
a.pop()
print(a)
a.remove(3)
print(a)
a.remove(a[4])
print(a)

Just like with strings, elements are indexed beginning with 0.

Lists can be constructed using ‘for’ and some conditional statements. These are called, ‘list comprehensions’. For example:

even_numbers = [x for x in range(100) if x % 2 == 0]
print(even_numbers)

List comprehensions can work on strings as well:

first_sentence = "It was a dark and stormy night."
characters = [x for x in first_sentence]
print(characters)

For more on comprehensions see: https://docs.python.org/2/tutorial/datastructures.html?highlight=comprehensions

Another similar feature is called ‘map’. Map applies a function to a list. The syntax is

map(aFunction, aSequence). Consider the following examples:

def sqr(x): return x ** 2
a = [2,3,4]
b = [10,5,3]
c = map(sqr,a)
print(c)
d = map(pow,a,b)
print(d)

Note that map is usually more efficient than the equivalent list comprehension or looping contruct.

Tuples

Tuples are like lists with one very important difference. Tuples are not changeable.

a = (1,2,3,4)
print(a)
a[1] = 2
a = (1,"string in a tuple",5.3)
b = (a,1,2,3)
print(a)
print(b)

As you can see, all of the other flexibility remains - so use tuples when you have a list that you do not want to modify.

One other handy feature of tuples is known as ‘tuple unpacking’. Essentially, this means we can assign the values of a tuple to a list of variable names, like so:

my_pets = ("Chestnut", "Tibbs", "Dash", "Bast")
(aussie,b_collie,indoor_cat,outdoor_cat) = my_pets
print(aussie)
cats=(indoor_cat,outdoor_cat)
print(cats)

Dictionaries

Dictionaries are unordered, keyed lists. Lists are ordered, and the index may be viewed as a key.

a = ["A","B","C","D"] #list example
print(a[1])
a = {'anItem': "A", 'anotherItem': "B",'athirdItem':"C",'afourthItem':"D"} # dictionary example
print(a[1])
a = {'anItem': "A", 'anotherItem': "B",'athirdItem':"C",'afourthItem':"D"} # dictionary example
print(a['anItem'])
print(a)

The dictionary does not order the items, and you cannot access them assuming an order (as an index does). You access elements using the keys.

Sets

Sets are unordered collections of unique elements. Intersections, unions and set differences are supported operations. They can be used to remove duplicates from a collection or to test for membership. For example:

from sets import Set
fruits = Set(["apples","oranges","grapes","bananas"])
citrus = Set(["lemons","oranges","limes","grapefruits","clementines"])
citrus_in_fruits = fruits & citrus   #intersection
print(citrus_in_fruits)
diff_fruits = fruits - citrus        # set difference
print(diff_fruits)
diff_fruits_reverse = citrus - fruits  # set difference
print(diff_fruits_reverse)
citrus_or_fruits = citrus | fruits     # set union
print(citrus_or_fruits)
a_list = ["a", "a","a", "b",1,2,3,"d",1]
print(a_list)
a_set = Set(a_list)  # Convert list to set
print(a_set)         # Creates a set with unique elements
new_list = list(a_set) # Convert set to list
print(new_list)        # Obtain a list with unique elements

More examples and details regarding sets can be found at: https://docs.python.org/2/library/sets.html

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文