我想通过使用带有某些条件的单个循环来创建多个列表。 我知道如何创建一个通过追加完成的列表,但是这里循环的所有结果都放在一个我不想要的列表中。 可以这么说,我们对前100个数字运行循环,我想创建多个列表,其中第一个列表包含直到5的数字,第二个从6到10的数字,第三个从11到15的数字,依此类推。 此代码仅适用于我创建的一个列表。
number = range(100)
first = []
for i in number:
first.append(i)
first
答案 0 :(得分:1)
类似的东西:
Traceback (most recent call last):
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\urllib3\connection.py", line 159, in _new_conn
(self._dns_host, self.port), self.timeout, **extra_kw)
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\urllib3\util\connection.py", line 57, in create_connection
for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\socket.py", line 748, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11004] getaddrinfo failed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\urllib3\connectionpool.py", line 600, in urlopen
chunked=chunked)
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\urllib3\connectionpool.py", line 343, in _make_request
self._validate_conn(conn)
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\urllib3\connectionpool.py", line 839, in _validate_conn
conn.connect()
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\urllib3\connection.py", line 301, in connect
conn = self._new_conn()
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\urllib3\connection.py", line 168, in _new_conn
self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x00000000072AF400>: Failed to establish a new connection: [Errno 11004] getaddrinfo failed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\adapters.py", line 449, in send
timeout=timeout
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\urllib3\connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\urllib3\util\retry.py", line 398, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='accounts.google.com', port=443): Max retries exceeded with url: /o/oauth2/token (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x00000000072AF400>: Failed to establish a new connection: [Errno 11004] getaddrinfo failed'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/udgtlvr/untitled4/bigquery", line 18, in <module>
project_id=project_id, credentials=credentials)
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas_gbq\gbq.py", line 906, in read_gbq
dialect=dialect, auth_local_webserver=auth_local_webserver)
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas_gbq\gbq.py", line 202, in __init__
self.credentials = self.get_credentials()
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas_gbq\gbq.py", line 216, in get_credentials
credentials = self.get_user_account_credentials()
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas_gbq\gbq.py", line 354, in get_user_account_credentials
credentials = app_flow.run_console()
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\google_auth_oauthlib\flow.py", line 364, in run_console
self.fetch_token(code=code)
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\google_auth_oauthlib\flow.py", line 241, in fetch_token
self.client_config['token_uri'], **kwargs)
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\requests_oauthlib\oauth2_session.py", line 221, in fetch_token
verify=verify, proxies=proxies)
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\sessions.py", line 581, in post
return self.request('POST', url, data=data, json=json, **kwargs)
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\requests_oauthlib\oauth2_session.py", line 360, in request
headers=headers, data=data, **kwargs)
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "C:\Users\udgtlvr\AppData\Local\Continuum\anaconda3\lib\site-packages\requests\adapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='accounts.google.com', port=443): Max retries exceeded with url: /o/oauth2/token (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x00000000072AF400>: Failed to establish a new connection: [Errno 11004] getaddrinfo failed'))
Process finished with exit code 1
I have install so many libraries Related to this issue.
输出:
l = []
for x in range(6, 102, 5):
l.append([y for y in range(x-5, x)])
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35],
[36, 37, 38, 39, 40],
[41, 42, 43, 44, 45],
[46, 47, 48, 49, 50],
[51, 52, 53, 54, 55],
[56, 57, 58, 59, 60],
[61, 62, 63, 64, 65],
[66, 67, 68, 69, 70],
[71, 72, 73, 74, 75],
[76, 77, 78, 79, 80],
[81, 82, 83, 84, 85],
[86, 87, 88, 89, 90],
[91, 92, 93, 94, 95],
[96, 97, 98, 99, 100]]
函数采用三个参数range
,start
和stop
。
答案 1 :(得分:1)
尝试一下,这将创建您想要的东西:
lists = []
for i in range(1, 100, 5): # range(start, end, size_of_each_list)
lists.append(list(range(i,i + 5)))
lists
将是:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28, 29, 30],
[31, 32, 33, 34, 35],
[36, 37, 38, 39, 40],
[41, 42, 43, 44, 45],
[46, 47, 48, 49, 50],
[51, 52, 53, 54, 55],
[56, 57, 58, 59, 60],
[61, 62, 63, 64, 65],
[66, 67, 68, 69, 70],
[71, 72, 73, 74, 75],
[76, 77, 78, 79, 80],
[81, 82, 83, 84, 85],
[86, 87, 88, 89, 90],
[91, 92, 93, 94, 95],
[96, 97, 98, 99, 100]]
答案 2 :(得分:0)
我将执行类似于以下内容的列表理解:
[[i, i+1, i+2, i+3, i+4] for i in range (1, 100, 5)]
输出看起来像这样:
[[1, 2, 3, 4, 5],
...,
[96, 97, 98, 99, 100]]
https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
答案 3 :(得分:0)
这是一种实现方法。基本上,您可以从列表中创建一个迭代器,然后从中获取所需的所有列表。
number = range(100)
number_iter = iter(number)
lists = []
while True:
try:
lists.append([next(number_iter) for _ in range(5)])
except StopIteration as e:
break
lists
这样做的好处是您的初始“号码”列表可以是任何内容...
答案 4 :(得分:0)
我会在第一个列表中使用第二个列表。
number = range(100)
cnt = 0
first = []
second = []
for i in number:
cnt += 1
second.append(i)
if cnt == 5:
first.append(second)
cnt = 0
second = []
first
输出:
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
...
[95, 96, 97, 98, 99]]
答案 5 :(得分:-1)
可能。我们可以通过在我们的globals()
环境中直接创建变量来做到这一点。
(如果locals()
仅应包含在封闭函数中,则使用它。)
您可以使用以下代码执行此操作:
# Run the loop
for i in range(100):
# for 0-4, list_name = 'list_1'
list_name = 'list_' + str(i//5 + 1)
# Try to append to that list
try:
globals()[list_name].append(i)
# If if doesn't exist, create it on the run!
except KeyError:
globals()[list_name] = [i]
此globals()[list_name] = [i]
首先:
list_name
变量。i
的列表。让我们将它们全部打印出来:
for i in range(20):
# Print list_1 through list_20
list_name = 'list_' + str(i+1)
print(list_name + ':', globals()[list_name])
您得到:
list_1: [0, 1, 2, 3, 4]
list_2: [5, 6, 7, 8, 9]
list_3: [10, 11, 12, 13, 14]
list_4: [15, 16, 17, 18, 19]
list_5: [20, 21, 22, 23, 24]
list_6: [25, 26, 27, 28, 29]
list_7: [30, 31, 32, 33, 34]
list_8: [35, 36, 37, 38, 39]
list_9: [40, 41, 42, 43, 44]
list_10: [45, 46, 47, 48, 49]
list_11: [50, 51, 52, 53, 54]
list_12: [55, 56, 57, 58, 59]
list_13: [60, 61, 62, 63, 64]
list_14: [65, 66, 67, 68, 69]
list_15: [70, 71, 72, 73, 74]
list_16: [75, 76, 77, 78, 79]
list_17: [80, 81, 82, 83, 84]
list_18: [85, 86, 87, 88, 89]
list_19: [90, 91, 92, 93, 94]
list_20: [95, 96, 97, 98, 99]
注意:为什么不来一些数字娱乐!请参阅python inflect软件包。