- 列表理解:列表理解是摆脱编写不必要的代码行的最好和有效的技术。阅读文章了解更多。
Printing a list: List are not printed according the user requirement. They are always printed in unwanted square brackets and single quotes. But there is trivial solution to print the list efficiently by using the string’s join method.
The join method turns the list into a string by casting each item into a string and connecting them with the string that join was called on.
```py
Declaring the list geekgeek = ['Geeks', 'Programming', 'Algorithm', 'Article']
Directly printing the listprint ("Simple List:", geek)
Printing the list by join methodprint ('List by using join method: %s' % ', ' .join(geek))
Direct use of join methodprint ('Direct apply the join method:',(", " .join(geek)))
```
```py
Output:
Simple List: ['Geeks', 'Programming', 'Algorithm', 'Article']
List by using join method: Geeks, Programming, Algorithm, Article
Direct apply the join method: Geeks, Programming, Algorithm, Article
```
炫酷的拉链招数
转置一个矩阵:你可以读到这里关于这个。
Partition a list into N groups: We used iter() as an iterator over a sequence.
```py
Declaring the list geekgeek = ['Sun', 'Flowers', 'Peoples', 'Animals', 'Day', 'Night']
partition = list(zip (*[iter(geek)] * 2))
print (partition)
```
```py
Output:
[('Sun', 'Flowers'), ('Peoples', 'Animals'), ('Day', 'Night')]
```
解释 : [iter(geek)] * 2 产生一个包含 geek[]列表 2 项的列表,即长度为 2 的列表。*arg 将序列解包为函数调用的参数。因此,我们将同一个迭代器传递给 zip()两次。
同时打印多个列表的项目
```py
list1 = [1, 3, 5, 7]
list2 = [2, 4, 6, 8]
Here zip() function takes two equal length list and merges them
together in pairsfor a, b in zip(list1,list2):
print (a, b)
```
```py
Output:
1 2
3 4
5 6
7 8
```
以字符串为输入,转换为列表:
```py
Reads a string from input and type case them to int
after splitting to white-spacesformatted_list = list(map(int, input().split()))
print(formatted_list)
```
```py
Input:
2 4 5 6
Output:
[2, 4, 5, 6]
```
将列表列表转换为单个列表
```py
import the itertoolsimport itertools
Declaring the list geekgeek = [[1, 2], [3, 4], [5, 6]]
chain.from_iterable() function returns the
elements of nested list
and iterate from first list
of iterable till the last
end of the listlst = list(itertools.chain.from_iterable(geek))
print(lst)
```
```py
Output:
[1, 2, 3, 4, 5, 6]
```
打印重复字符:任务是打印这样的图案 Geeeeekkkkss。因此,我们可以轻松打印此图案,而无需使用 for loop。
```py
+ used for string concatenation
To repeat the character n times, just multiply n
with that characterprint ("G" + "e"5 + "k"4 + "s"*2)
```
```py
Output:
Geeeeekkkkss
```
本文由 Shubham Bansal 供稿。如果你喜欢 GeeksforGeeks 并想投稿,你也可以使用contribute.geeksforgeeks.org写一篇文章或者把你的文章邮寄到 contribute@geeksforgeeks.org。看到你的文章出现在极客博客主页上,帮助其他极客。